猿问

服务中的广播接收器

我正在尝试BroadcastReceiver在内启动Service。我正在尝试做的是后台运行service,该后台会收集传入的短信并记录传入的电话。我认为最好的方法是让service跑步机与可以编录其中一个节目的广播接收器合并。


我该怎么做?我已经启动并运行了我的服务。


12345678_0001
浏览 383回答 3
3回答

炎炎设计

由于您的服务已经设置,只需在您的服务中添加广播接收器:private final BroadcastReceiver receiver = new BroadcastReceiver() {&nbsp; &nbsp;@Override&nbsp; &nbsp;public void onReceive(Context context, Intent intent) {&nbsp; &nbsp; &nbsp; String action = intent.getAction();&nbsp; &nbsp; &nbsp; if(action.equals("android.provider.Telephony.SMS_RECEIVED")){&nbsp; &nbsp; &nbsp; &nbsp; //action for sms received&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//action for phone state changed&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp; &nbsp;}};在您的服务中onCreate执行以下操作:IntentFilter filter = new IntentFilter();filter.addAction("android.provider.Telephony.SMS_RECEIVED");filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);filter.addAction("your_action_strings"); //further morefilter.addAction("your_action_strings"); //further moreregisterReceiver(receiver, filter);并在您的服务中onDestroy:unregisterReceiver(receiver);并且您很高兴收到您提到的过滤器的广播onCreate。如果需要,请确保添加任何权限。例如<uses-permission android:name="android.permission.RECEIVE_SMS" />

慕田峪7331174

Service如果尚未运行,则此实现将启动,如果已运行,Intent则将传递新的(用于检索onStartCommand)。如果你只希望它运行的时候Service是实时的,你可以以编程方式启用/禁用Receiver通过组件PackageManager的setComponentEnabledSetting()。
随时随地看视频慕课网APP

相关分类

Android
我要回答