0

我的应用程序每秒获取一次 GPS 更新。它还每秒获取一次 Wifi 连接的 RSSI 值。我面临的问题是,广播接收器永远不会被调用。有人可以指出我做错了什么。我查看了很多 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 地址,设备启动服务器或客户端线程。这部分代码在我注册广播接收器后紧随其后

4

1 回答 1

1

请注意,您broadcast在清单中声明了一个名称PingActivity,并且您的实现类被称为您myWifiReceiver必须将其重命名为 PingActivity,并且还使您的广播成为一个单独的类。

于 2013-10-08T19:44:09.337 回答