问题描述
这是我的广播接收器.
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 } }
<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模式.问题描述
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.