我的应用程序每秒都会获得一次GPS更新。它还可以每秒获取一次Wifi连接的RSSI值。我面临的问题是,BroadcastReceiver永远不会被调用。有人可以指出我做错了什么。我查看了很多stackoverflow问题以及其他网站,但我无法弄清楚我做错了什么。我的代码如下:
final String locAction = "com.android.ping.STARTGPS";
PendingIntent pIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(locAction);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
Log.i(TAG,"PING: GPS not enabled");
} else {
Log.i(TAG,"PING: GPS enabled");
pIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_time_BW_Updates, MIN_Distance_Change_For_Updates, pIntent);
registerReceiver(myWifiReceiver, new IntentFilter(locAction));
Log.i(TAG,"PING: adding GPS status listener");
}
}
广播接收器:
protected BroadcastReceiver myWifiReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent){
Log.i(TAG, "PING: inside onReceive");
if (intent.getAction().equals(locAction)){
String locationKey = LocationManager.KEY_LOCATION_CHANGED;
Location location = (Location) intent.getExtras().get(locationKey);
Log.i(TAG, "PING: location is " + location.getLatitude() + ", " + location.getLongitude());
setLocation(location.getLatitude(), location.getLongitude());
try {
WifiInfo(); //Calls the function that gets the RSSI
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
意图未注册:
@Override
protected void onStop() {
super.onStop();
locationManager.removeUpdates(pIntent);
unregisterReceiver(myWifiReceiver);
}
我的清单文件,我注册了BroadcastReceiver:
<receiver android:name="PingActivity" >
<intent-filter>
<action android:name="com.android.ping.STARTGPS" />
</intent-filter>
</receiver>
编辑1: 我还必须补充一点,我在应用程序中硬编码IP地址(现在)并将其部署在2个不同的设备上。根据IP地址,设备启动服务器或客户端线程。在我注册broadcastReceiver
之后,这部分代码就紧随其后答案 0 :(得分:1)
请注意,您在清单中使用名称broadcast
声明PingActivity
,并且您的实现类名为myWifiReceiver
,您必须将其重命名为PingActivity,并且
将你的广播分开。