服务中的广播接收器 [英] Broadcast Receiver within a Service

查看:34
本文介绍了服务中的广播接收器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Service 中启动一个 BroadcastReceiver.我想要做的是让后台运行 service 去收集传入的短信,并记录传入的电话.我认为最好的方法是让 service 运行,其中包含一个可以编目的广播接收器.

I am trying to start up a BroadcastReceiver within a Service. What I am trying to do is have a background running service going that collects incoming text messages, and logs incoming phone calls. I figured the best way to go about this is to have a service running that incorporates a broadcast receiver that can catalog either.

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

How do i go about doing this? I already have my service up and running.

推荐答案

由于您的服务已经设置,只需在您的服务中添加一个广播接收器:

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

在您的服务的 onCreate 中执行以下操作:

in your service's onCreate do this:

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 more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

并在您的服务的 onDestroy 中:

and in your service's onDestroy:

unregisterReceiver(receiver);

并且您很高兴接收您在 onCreate 中提到的过滤器的广播.如果需要,请确保添加任何权限.例如

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

<uses-permission android:name="android.permission.RECEIVE_SMS" />

这篇关于服务中的广播接收器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆