Java Android停止唤醒服务
当我关闭一个特殊活动和整个应用程序时,我想停止WakefulService。因此,我将其写入onDestroy()和onBackPressed()中调用的函数中Java Android停止唤醒服务,java,android,service,Java,Android,Service,当我关闭一个特殊活动和整个应用程序时,我想停止WakefulService。因此,我将其写入onDestroy()和onBackPressed()中调用的函数中 stopService(新意图(getApplicationContext(),gcminentservice.class)) 但该服务仍在运行。有人能帮我吗 服务: 您应该等待任务完成,请看这里: 要使任务中止,请设置一些全局变量(即在SharedReferences中),该变量将指示应取消/中止任务。然后IntentService
stopService(新意图(getApplicationContext(),gcminentservice.class))代码>
但该服务仍在运行。有人能帮我吗
服务:
您应该等待任务完成,请看这里:
要使任务中止,请设置一些全局变量(即在SharedReferences中),该变量将指示应取消/中止任务。然后IntentService将自行关闭。另一种可能性是将中止作为任务执行:
// Pseudocode for example cancellable WakefulIntentService
public class MyService extends WakefulIntentService {
AtomicBoolean isCanceled = new AtomicBoolean(false);
public static void cancelTasks(Context context) {
Intent intent = new Intent(context, SynchronizationService.class);
intent.putExtra("action", "cancel");
context.startService(intent);
}
public MyService () {
super("MyService");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.hasExtra("action")) {
// Set the canceling flag
if ( intent.getStringExtra("action").equals("cancel") ) {
isCanceled.set(true);
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void doWakefulWork(Intent intent) {
// Clean up the possible queue
if (intent.hasExtra("action")) {
boolean cancel = intent.getStringExtra("action").equals("cancel");
if (cancel) {
return;
}
}
// here do some job
while ( true ) {
/// do some job in iterations
// check if service was cancelled/aborted
if ( isCanceled.get() )
break;
}
}
}
如果您想中止服务,请拨打:
MyService.cancelTasks(getActivity());
您可以将所有这些取消代码放入基类,使其看起来更干净。如果您希望应用程序停止响应GCM消息,则需要禁用设置为接收GCM广播的广播接收器。您可以通过PackageManager
上的setComponentEnabledSetting()
禁用它。请记住,您以后需要重新启用它才能再次接收GCM消息。“当我关闭整个应用程序时”——Android中没有关闭应用程序的概念。“我想停止我的WakefulService”--如果您的服务确实是一个名为的IntentService
,那么它将只运行足够长的时间来处理onHandleIntent()
,然后将自行停止。。。除非你做了些什么来阻止。您有什么证据表明该服务仍在运行?startWakefulService(context,(intent.setComponent(comp))代码>这是Google Cloud MessagingLet的WakefulIntentService请重试:您有什么证据表明该服务仍在运行?啊,对不起,是GCM,每次我从服务器发送消息时,我都会通过该服务收到通知,所以它仍在运行。我将最后一次尝试:您有什么证据表明该服务仍在运行?GCM消息被传送到广播接收器
。BroadcastReceiver
将响应此类广播,直到您禁用该组件。如果您有BroadcastReceiver
将工作委托给IntentService
,则IntentService
将一直运行,直到onHandleIntent()
返回。因此,您的IntentService
仍然能够响应GCM消息,这并不意味着IntentService
正在持续运行。IMHO,IntentService
不是为while(true)
场景而设计的WakefulIntentService
并不是为while(true)
场景而设计的。在任何一种情况下,都可以推出您自己的服务,该服务具有适合您需要的线程模型(并根据需要提供自己的WakeLock
)。工作时间要短,否则定期服务会更好。