我有一个绑定服务,我在创建的库模块中设置了它。
如果这不是一个库模块,我的问题会很简单,因为我需要其他模块动态。
目前的应用程序使用库模块通过Wifi Direct在两部手机之间搜索和创建连接(到目前为止没有问题)。
我现在的问题是我的应用程序(我正在测试它,以确保库模块没有丢失任何东西)不知道两部手机何时"连接"。
我已经尝试了一段时间的循环来不断请求内容并循环直到它不为空,这在技术上会起作用吗?然而,我在这方面运气不佳。
我本来想实现一个等待功能,但这将是最后的手段!
我正在使用android指南来创建我的库链接
实际问题
我正在尝试获取有关连接的信息以显示给用户,显然,如果连接尚未建立,它将为空!因此给我带来了问题。
我找到的一个解决方案是逐步通过并手动等待,直到另一部手机接受连接并成功连接,然后继续请求信息等
如果有任何问题,请告诉我,因为我知道这很令人困惑!
更新:当您的库检测到成功的P2P连接时,您将希望在库中使用sendBroadcast()向应用程序发送意向。只有当当前打开了"活动"时,您才可能希望在应用程序中接收意向。请参阅下面的新代码:
请注意,这是在建立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
}
};