use*_*676 32 android foreground-service
我正在尝试停止作为前台服务运行的服务.
目前的问题是,当我打电话时stopService(),通知仍然存在.
所以在我的解决方案中,我添加了一个我正在注册的接收器 onCreate()
在onReceive()我调用的方法内部stopforeground(true),它隐藏了通知.然后stopself()停止服务.
onDestroy()我在里面注册了接收器.
有没有更合适的方法来处理这个?因为stopService()根本不起作用.
@Override
public void onDestroy(){
unregisterReceiver(receiver);
super.onDestroy();
}
Run Code Online (Sandbox Code Playgroud)
Ily*_*man 54
从您的活动调用中startService(intent)传递一些数据,这些数据将代表停止服务的密钥.
从您的服务电话stopForeground(true),然后stopSelf()在它之后.
Ela*_*lad 28
从活动使用中启动和停止前台服务:
//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);
Run Code Online (Sandbox Code Playgroud)
在您的前台服务中 - 使用(至少)此代码:
@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);
stopSelf();
}
return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)
Ahm*_*hid 11
As stated here: https://developer.android.com/guide/components/services#Stopping
A started service must manage its own lifecycle. That is, the system doesn't stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. The service must stop itself by calling stopSelf(), or another component can stop it by calling stopService().
Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.
So you can call stopService() from the activity that you used to call startService(). I have done that right here:
start_button.setOnClickListener {
applicationContext.startForegroundService(Intent(this, ServiceTest::class.java))
}
stop_button.setOnClickListener {
applicationContext.stopService(Intent(this, ServiceTest::class.java))
}
Run Code Online (Sandbox Code Playgroud)
I created two buttons to start and stop the service and it works.
从活动
stopService(new Intent(this, ForegroundService.class));
Run Code Online (Sandbox Code Playgroud)
从服务本身
stopForeground(true);
stopSelf()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22652 次 |
| 最近记录: |