问题描述
我已经看到了如何实现一个BroadcastReceiver几个例子,但是我应该如何实现有反应的一些未决的意图(例如呼入电话)服务...其实我想知道同样的问题,但在活动..你明明有延伸服务或活动)的一类,因此它不能也延长了BroadcastReceiver ...看起来,我们不能让平台意识服务和/或工作之外的活动?
I have seen several examples of how to implement a BroadCastReceiver, but how should I implement a Service that has to react to some pending Intent (for example incoming phone call)...Actually I was wondering about the same "problem" but in an Activity..You obviously have a class which extends a Service or an Activity) so it cannot also extend BroadCastReceiver...It looks like we cannot make "platform-aware" services and/or Activties?
推荐答案
要注册一个活动,收到一定的目的,你需要:
To register an activity to receive a certain intent you need to:
// 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;
}
}
然后,你还需要增加一个意图过滤器,以你的清单:
Then you will also need to add an intent-filter to your manifest:
<activity android:name=".MyActivity" android:label="@string/name" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</activity>
这篇关于服务与一个BroadcastReceiver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!