我已经看到了如何实现BroadCastReceiver的几个例子,但是我应该如何实现必须对一些待处理的Intent(例如来电)做出反应的服务…
其实我是想知道同样的“问题”,但在一个活动..
你显然有一个扩展一个服务或活动的类),因此它不能扩展BroadCastReceiver …
看起来我们不能使“平台感知”服务和/或活动?
其实我是想知道同样的“问题”,但在一个活动..
你显然有一个扩展一个服务或活动的类),因此它不能扩展BroadCastReceiver …
看起来我们不能使“平台感知”服务和/或活动?
解决方法
要注册一个活动以获得某种意图,您需要:
// Flag if receiver is registered private boolean mReceiversRegistered = false; // I think this is the broadcast you need for something like an incoming call private String INCOMING_CALL_ACTION = "android.intent.action.PHONE_STATE"; // Define a handler and a broadcast receiver private final Handler mHandler = new Handler(); private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context,Intent intent) { // Handle reciever String mAction = intent.getAction(); if(mAction.equals(INCOMING_CALL_ACTION) { // Do your thing } } @Override protected void onResume() { super.onResume(); // Register Sync Recievers IntentFilter intentToReceiveFilter = new IntentFilter(); intentToReceiveFilter.addAction(INCOMING_CALL_ACTION); this.registerReceiver(mIntentReceiver,intentToReceiveFilter,null,mHandler); mReceiversRegistered = true; } @Override public void onPause() { super.onPause(); // Make sure you unregister your receivers when you pause your activity if(mReceiversRegistered) { unregisterReceiver(mIntentReceiver); mReceiversRegistered = false; } }
那么您还需要在清单中添加意图过滤器:
<activity android:name=".MyActivity" android:label="@string/name" > <intent-filter> <action android:name="android.intent.action.PHONE_STATE" /> </intent-filter> </activity>