在服务广播接收机接收机

2023-09-12 00:43:02 作者:傲血狂沙

我试图启动一个的BroadcastReceiver 服务。我所试图做的是有一个后台运行服务将收集传入的文本信息,并记录电话来电。我想通去了解,这是有一个服务运行,包含了广播接收器,可以任意目录的最佳方式。

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

unregisterReceiver(receiver);

,你是好去接收广播的什么都过滤你提到的onStartCommand。确保在需要时添加任何权限。对于例如。

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

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