在设备上使用IntentFilter分辨率的奇怪行为

时间:2011-02-24 19:47:56

标签: android android-intent

我正在试验requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent)和BroadcastReceiver。代码如下:

// PendingLocationDemo.java
public class PendingLocationDemo extends Activity {

    public TextView output;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        output = (TextView) findViewById(R.id.output);
        SomeReceiver receiver = new SomeReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("some_action");
        // filter.addAction("some_other_action");
        // filter.addAction("still_something_different");
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        getApplicationContext().registerReceiver(receiver, filter);
        Intent intent = new Intent();
        intent.setAction("some_action");
        PendingIntent pending = PendingIntent.getBroadcast(
                getApplicationContext(), 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        // Get the location manager
        LocationManager locationManager = (LocationManager) 
                getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 3000, 0, pending);
    }

    protected void someCallback(Intent intent) {
        printObject(intent);
    }
}

// SomeReceiver.java
public class SomeReceiver extends BroadcastReceiver {

    PendingLocationDemo caller;

    public SomeReceiver(PendingLocationDemo caller) {
        this.caller = caller;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        caller.someCallback(intent);
    }
}

当我在设备上运行它时,输出取决于我用于IntentFilter中的操作的值。

  • 表示“some_action”,输出为: 意图{act = some_action cat = [android.intent.category.DEFAULT](有额外内容)}
  • 表示“some_other_action”,输出为: 意图{act = some_other_action(has extras)}
  • 对于“still_something_different”,我没有收到更新。

这种不一致的行为是否有合理的解释?

1 个答案:

答案 0 :(得分:0)

这种奇怪的行为是由于广播接收器的注册。您可以在位置侦听器中编写代码,而不是注册广播接收器,位置侦听器也是广播接收器,并在后台侦听位置更新。

final LocationManager locationManager = (LocationManager) context
        .getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {

    public void onLocationChanged(Location location) {
        // Code for action you wish to perform on Location Changed.
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}
};
// ...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
            3000, locationListener);

希望它有所帮助。