更新:当您的库检测到成功的 P2P 连接时,您将希望在库中使用 sendBroadcast() 向您的应用发送意图。仅当当前打开 Activity 时,您可能希望在您的应用程序中接收意图。请参阅下面的新代码:
看到这是在建立 P2P 连接的情况下添加的,请注意您应该将 com.yourapp.example 替换为您的包名称:
Intent i = new Intent("com.yourapp.example.P2PCONNECTED");
context.sendBroadcast(i);
在您的库中定义 BroadcastReceiver 的代码:
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
}
}
}
}
};
然后在您应用中的任何活动或片段中,您可能希望在 onResume() 中注册并在 onPause() 中取消注册,请参见以下代码:
@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
}
};