Raj*_*esh 5 android android-broadcastreceiver
目前我有用于收听呼叫状态事件的广播接收器.我已经注册了Broadcast Receiver,AndroidManifest.xml如下所示.
<receiver android:name=".api.PhoneCallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
当应用程序启动时,此广播接收器已注册为侦听状态事件,并且根据CALL_STATE我正在管理我的应用程序.
手机重启后工作正常.手机重启后,此广播接收器停止工作.我知道我必须为BOOT_COMPLETED系统的监听事件注册接收器.
我所做的如下所示:
<receiver android:name=".api.PhoneCallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
我还给出了获取BOOT_COMPLETED系统事件的权限.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Run Code Online (Sandbox Code Playgroud)
但不知怎的,它不起作用.我正在考虑制作只听BOOT_COMPLETED事件的新广播接收器,但问题就在于此
所以我的问题是,当有来电时我怎么能启动这个电话呼叫监听器广播接收器?
如何从另一个广播接收器注册广播接收器
我是否必须将现有的广播接收器代码移至服务中,以便我可以从Boot Receiver启动服务?
任何帮助将不胜感激.
欢迎任何其他答案。
我已经通过创建新的广播接收器解决了这个问题,并且onReceive()当手机重新启动时将调用该广播接收器的方法,然后我动态注册了READ_PHONE_STATE广播接收器,它也是清单注册的接收器。
下面是代码:
AndroidManifest.xml:
<receiver android:name=".api.ServiceStarter">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
广播接收器:
public class ServiceStarter extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
PhoneCallReceiver receiver = new PhoneCallReceiver();
context.getApplicationContext().registerReceiver(receiver, filter);
}
}
Run Code Online (Sandbox Code Playgroud)
您必须使用应用程序上下文注册接收者,如下所示:
context.getApplicationContext().registerReceiver(receiver, filter);
Run Code Online (Sandbox Code Playgroud)
代替
context.registerReceiver(receiver, filter);
Run Code Online (Sandbox Code Playgroud)
否则你会得到以下异常:
java.lang.RuntimeException:无法启动接收器com.ecosmob.contactpro.api.ServiceStarter:android.content.ReceiverCallNotAllowedException:不允许BroadcastReceiver组件注册接收意图
我希望它能帮助其他人!
| 归档时间: |
|
| 查看次数: |
1601 次 |
| 最近记录: |