我认为你不应该这样做。
我可以看到您的方法中至少有两个缺点:
- 警报器会太忙
- 你不能从另一个广播接收器注册一个广播接收器
另一种更好的方法是使用 handler.postDelayed 方法:
您的服务应该要求处理程序在几秒钟内(当您需要时)自己回来
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
//do some treatment based on the action intent
//first action is used to compute 10 time stamps
//second action is used to treat task
//then use a handler to reschedule your service
handler.postDelayed( new Runnable() {
@Override
public void run() {
onStartCommand( <intent for action 2>, flags, startId);
Log.v( LOG_TAG, "timer sending intent");
}
}, delayInMsToNextTask );
}//met
因此,广播接收器没有办法。
我忘了说您应该在清单文件中为两个意图操作注册服务。
<service android:name="myService">
<intent-filter>
<action android:name="action1" />
</intent-filter>
<intent-filter>
<action android:name="action2" />
</intent-filter>
</service>
此外,添加单个操作可能会很好,但要区分 onStartCommand 应该在具有相同名称的意图中使用 extras 做什么。然后,您的服务将在清单中注册单个操作。
下次如果你觉得你的解释不是很清楚,请发一些代码/伪代码。
问候,
斯蒂芬