Updated: You will want to use sendBroadcast() in your library to send an intent to your app when your library detects a successful P2P connection. You will probably want to receive the intent in your app only if there is an Activity currently open. See new code below:
See that this was added to case where there is a P2P connection established, note that you should replace com.yourapp.example with your package name:
Intent i = new Intent("com.yourapp.example.P2PCONNECTED");
context.sendBroadcast(i);
Code to define the BroadcastReceiver in your library:
WiFiDirectFilter = new IntentFilter(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
WiFiDirectFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
WiFiDirectFilterBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("MyApp", action);
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Log.i("MyApp", "WifiDirect WIFI_P2P_STATE_CHANGED_ACTION Enabled: true");
//WiFi Direct Enabled
//Do something....
}
else {
Log.i("MyApp", "WifiDirect WIFI_P2P_STATE_CHANGED_ACTION Enabled: false");
//WiFi Direct not enabled...
//Do something.....
}
}
else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(networkInfo != null) {
boolean isWiFiDirectConnected = networkInfo.isConnected();
Log.i("MyApp", "WifiDirect WIFI_P2P_CONNECTION_CHANGED_ACTION Connected: " + );
if (isWiFiDirectConnected){
//WiFi Direct connected!
//Send Broadcast to your app
Intent i = new Intent("com.yourapp.example.P2PCONNECTED");
context.sendBroadcast(i);
}
else{
//WiFi Direct not connected
//Do something
}
}
}
}
};
Then in any activity or fragment in your app, you would want to register in onResume() and unregister in onPause(), see code below:
@Override
public void onResume() {
super.onResume();
IntentFilter iFilter= new IntentFilter("com.yourapp.example.P2PCONNECTED");
//iFilter.addAction("someOtherAction"); //if you want to add other actions to filter
this.registerReceiver(br, iFilter);
}
@Override
public void onPause() {
this.unregisterReceiver(br);
super.onPause();
}
private BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("com.yourapp.example.P2PCONNECTED")){
this.runOnUiThread(mUpdateP2PStatus);
}
}
};
private final Runnable mUpdateP2PStatus= new Runnable() {
@Override
public void run() {
//TODO: Update your UI here
}
};