Reputation: 1151
I'm using the Android Wifi P2P technology in my android application to send simple data transmissions between multiple devices. I'm reading the Developer Guide for Wifi p2p, but the implementation seems like it is only built for one activity to use the Wifi direct service.
Following the guide, I created this BroadcastReceiver class to listen for Wifi Direct events:
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
public class WifiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager manager;
private Channel channel;
private WifiActivity activity;
public WifiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel, WifiActivity activity){
this.manager = manager;
this.channel = channel;
this.activity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
// Check to see if Wi-Fi is enabled and notify appropriate activity
}else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
// Call WifiP2pManager.requestPeers() to get a list of current peers
}else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
// Respond to new connection or disconnections
}else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
// Respond to this device's wifi state changing
}
}
}
However, the constructor seems to only work with one activity. Do I have to make a receiver for each and every activity that uses Wifi Direct? How do I pass the connection to different activities without having to set up the connection each time (i.e. find peers, connect to peer, etc)?
Upvotes: 3
Views: 1732
Reputation: 113
Although the answer is too late but since no one answered it, I thought of providing the solution.
You need to register the broadcast receiver with multiple activities, and change your constructor with the following code
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel,Context activity) {
super();
this.manager = manager;
this.channel = channel;
this.activity = activity;
}
And wherever you need to change the code according to the activity, just check this
if(activity instanceof yourActivityName){
// your code based on the current activity
}
And register your broadcastreciever in your activity with this
receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
Hope this helps
Upvotes: 4