在安卓系统中,从广播接收器向正在运行的服务发送一个意图[英] Sending an intent from broadcast receiver to a running service in android

本文是小编为大家收集整理的关于在安卓系统中,从广播接收器向正在运行的服务发送一个意图的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

这是我的广播接收器.

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context ctx, Intent intent) {
            Log.d(DEBUG_TAG, SmsReceiver.class.getSimpleName()+ " action: " + intent.getAction());
            // here is codes for sending intent to my running service 

    }  }

这里是我清单XML文件中的广播接收器和服务节点.

<service android:name=".SMSGatewayService" />

<receiver android:name=".SmsReceiver">
    <intent-filter>
         <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

如何从广播接收器发送到运行服务的意图. 提前谢谢.

推荐答案

理想情况下,您没有运行服务.当他们做某事时,服务应该只在记忆中,并且在短信到达时,您的代码将无法做任何事情.

所说,您的接收器可以调用startService().这将Intent传递给onStartCommand(),无论是在运行还是不运行.理想情况下,您的服务是一个IntentService,一个设计用于使用命令模式并在完成处理命令时关闭.

此外,由于SMS消息可以在设备睡眠时到达,因此您可能需要使用WakeLock以确保设备保持唤醒,以便控制传递给服务,并为服务执行任何操作它在做.一种方法是使用我的 WakefulIntentService ,它包装IntentService + WakeLock模式.

本文地址:https://www.itbaoku.cn/post/102463.html

问题描述

Here is a my broadcast receiver.

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context ctx, Intent intent) {
            Log.d(DEBUG_TAG, SmsReceiver.class.getSimpleName()+ " action: " + intent.getAction());
            // here is codes for sending intent to my running service 

    }  }

here is broadcast receiver and service nodes in my manifest xml file.

<service android:name=".SMSGatewayService" />

<receiver android:name=".SmsReceiver">
    <intent-filter>
         <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

How can i send intent from broadcast receiver to my running service. thanks in advance.

推荐答案

Ideally, you don't have a running service. Services should only be in memory when they are doing something, and odds are your code won't be doing anything when an SMS arrives.

That being said, your receiver can call startService(). This passes an Intent to onStartCommand() of the service, whether it is already running or not. Ideally, your service is an IntentService, one designed to work with the command pattern and to shut down when it is done processing a command.

Also, since SMS messages can arrive while the device is asleep, you will probably need to employ a WakeLock to ensure the device stays awake long enough for control to pass to the service and for the service to do whatever it is it is doing. One approach for this is to use my WakefulIntentService, which wraps up the IntentService+WakeLock pattern.