Monday, March 13, 2017

Android - At the top speed share files with Wi-Fi Direct

To transfer files at top speed, Android 4.0(API level 14) or later devices with the hardware to connect directly to each other via Wi-Fi without an intermediate access point. Using these APIs, you can discover and connect to other devices when each device supports Wi-Fi Direct, then communicate over a speedy connection across distances much longer than a Bluetooth connection. This is useful for applications that share data among users, such as a multi-player game, Off-line chat or a media sharing application.

Something more about wi-fi direct.

1. For peer-to-peer data transmission, it does not use any kind of traditional home, office or hotspot network.
2. For Security purpose, it uses WPA2 encryption protection.
3. It can transfer data at the speed of 2.5 to 3.0 Mbps.
4. Wi-Fi Direct can operate at up to 100m. Some reference site says 656 feet too.
5. We can also set up group between devices for which hardware support is offered for wifi direct.


Below is the process explained to perform Wi-Fi Direct feature.


1. Set up Application permissions.


In order to use Wi-Fi Direct, add the following permissions to your manifest. Wi-Fi Direct doesn't require an internet connection, but it does use standard Java sockets, which require the INTERNET permission.

   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

2. Set up a Broadcast Receiver and Peer-to-Peer Manager.


To use Wi-Fi Direct, you need to listen for broadcast intents that tell your application when certain events have occurred. In application, instantiate an IntentFilter and set it to listen for the following:

    @Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {          
            if (intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1) == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                mainPresenterImp.setIsWifiP2pEnabled(true);
            } else {
                mainPresenterImp.setIsWifiP2pEnabled(false);
            }
        } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
                manager.requestPeers(channel, mainPresenterImp);
        } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
            if (intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO).isConnected()) {
                manager.requestConnectionInfo(channel, mainPresenterImp);
            } else {
                mainPresenterImp.resetData();
            }
        } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
            mainPresenterImp.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
        }
    }

  Now, Create broadcast receiver and register it when the screen is active.

  @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intentFilter = new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

        manager = (WifiP2pManager) activity.getSystemService(Context.WIFI_P2P_SERVICE);
        channel = manager.initialize(activity, activity.getMainLooper(), null);
    
        receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
    }

Finally, Add code to register the intent filter and broadcast receiver when your main activity is active, and unregister them.

@Override
    public void onResume() {
        super.onResume();
        registerReceiver(receiver, intentFilter);
    }

3. Initiate Peer Discovery.


To start searching for nearby devices with Wi-Fi Direct, call discoverPeers()  method.

manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

            @Override
            public void onSuccess()
            {
                Toast.makeText(mActivity, "Discovery Initiated",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int reasonCode)
            {
                Toast.makeText(mActivity, "Discovery Failed : " + reasonCode,
                        Toast.LENGTH_SHORT).show();
            }
        });

4. Fetch the List of Peers.

Now fetch the list of peers. First, implement the WifiP2pManager.PeerListListener interface, which provides information about the peers that Wi-Fi Direct has detected. The following code snippet illustrates this.

private PeerListListener peerListListener = new PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peerList) {

            // Out with the old, in with the new.
            peers.clear();
            peers.addAll(peerList.getDeviceList());

            // If an AdapterView is backed by this data, notify it
            // of the change.  For instance, if you have a ListView of available
            // peers, trigger an update.
            ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();
            if (peers.size() == 0) {
                Log.d(WiFiDirectActivity.TAG, "No devices found");
                return;
            }
        }
    }

5. Connect to a Peer.

In order to connect to a peer, create a new WifiP2pConfig object, and copy data into it from the WifiP2pDevice representing the device you want to connect to. Then call the connect() method.

    @Override
    public void connect() {
        // Picking the first device found on the network.
        WifiP2pDevice device = peers.get(0);

        WifiP2pConfig config = new WifiP2pConfig();
        config.deviceAddress = device.deviceAddress;
        config.wps.setup = WpsInfo.PBC;

        mManager.connect(mChannel, config, new ActionListener() {

            @Override
            public void onSuccess() {
                // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
            }

            @Override
            public void onFailure(int reason) {
                Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

6. Connection Information Available.

WifiP2pManager.ConnectionInfoListener interface. Its onConnectionInfoAvailable() callback will notify you when the state of the connection changes. In cases where multiple devices are going to be connected to a single device (like a game with 3 or more players, or a chat app), one device will be designated the "group owner".

   @Override
    public void onConnectionInfoAvailable(final WifiP2pInfo info) {

        InetAddress groupOwnerAddress = info.groupOwnerAddress.getHostAddress());

        // After the group negotiation, we can determine the group owner.
        if (info.groupFormed && info.isGroupOwner) {
            // Do whatever tasks are specific to the group owner.
            // One common case is creating a server thread and accepting
            // incoming connections.
        } else if (info.groupFormed) {
            // The other device acts as the client. In this case,
            // you'll want to create a client thread that connects to the group
            // owner.
        }
    }

"groupOwnerAddress" provide the address of the device, By using that address we can share files, implement off-line chat Application
So, share a bit at top speed.
Share:

Get it on Google Play

React Native - Start Development with Typescript

React Native is a popular framework for building mobile apps for both Android and iOS. It allows developers to write JavaScript code that ca...