Sending an intent from broadcast receiver to a running service in android

做~自己de王妃 提交于 2019-12-09 01:52:35

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4420495/sending-an-intent-from-broadcast-receiver-to-a-running-service-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!