我试图停止作为前台服务运行的服务。
当前的问题是,当我调用stopService()
时,通知仍然保持不变。
因此,在我的解决方案中,我添加了一个接收器,我在onCreate()
中注册它
在onReceive()
方法中,我调用stopforeground(true)
,它隐藏通知。然后stopself()
停止服务。
在onDestroy()
内部,我取消了接收器的注册。
有更合适的方法来处理这件事吗?因为stopService()根本无法工作。
@Override
public void onDestroy(){
unregisterReceiver(receiver);
super.onDestroy();
}
发布于 2013-12-31 12:22:58
startService(intent)
并传递一些数据,表示停止服务的键。stopForeground(true)
stopSelf()
就在后面。发布于 2018-06-16 14:02:25
要从活动中启动和停止前台服务,请使用:
//start
Intent startIntent = new Intent(MainActivity.this, ForegroundService.class);
startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(startIntent);
//stop
Intent stopIntent = new Intent(MainActivity.this, ForegroundService.class);
stopIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION);
startService(stopIntent);
在前台服务中--使用(至少)以下代码:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Start Foreground Intent ");
// your start service code
}
else if (intent.getAction().equals( Constants.ACTION.STOPFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Stop Foreground Intent");
//your end servce code
stopForeground(true);
stopSelfResult(startId);
}
return START_STICKY;
}
发布于 2019-08-06 04:23:47
如前所述:https://developer.android.com/guide/components/services#Stopping
已启动的服务必须管理自己的生命周期。也就是说,除非系统必须恢复系统内存,而且服务在onStartCommand()返回后继续运行,否则系统不会停止或破坏服务。服务必须通过调用stopSelf()来停止自身,或者另一个组件可以通过调用stopSelf()来停止它
一旦请求停止使用stopSelf()或stopService(),系统就会尽快销毁服务。
因此,您可以从用于调用stopService()的活动中调用startService()。我就在这里做过:
start_button.setOnClickListener {
applicationContext.startForegroundService(Intent(this, ServiceTest::class.java))
}
stop_button.setOnClickListener {
applicationContext.stopService(Intent(this, ServiceTest::class.java))
}
我创建了两个按钮来启动和停止服务,它可以工作。
https://stackoverflow.com/questions/20857120
复制相似问题