什么是停止作为前台运行的服务的正确方法

问题描述 投票:25回答:3

我正在尝试停止作为前台服务运行的服务。

目前的问题是,当我打电话给stopService()时,通知仍然存在。

所以在我的解决方案中,我添加了一个接收器,我正在onCreate()中注册

onReceive()方法内部,我打电话给stopforeground(true),它隐藏了通知。然后stopself()停止服务。

onDestroy()里面我没有注册接收器。

有没有更合适的方法来处理这个问题?因为stopService()根本不起作用。

@Override
public void onDestroy(){
  unregisterReceiver(receiver);
  super.onDestroy();
}
android foreground-service
3个回答
51
投票

从您的活动中调用startService(intent)并传递一些数据,这些数据将代表停止服务的关键。

从你的服务电话stopForeground(true)然后stopSelf()就在它之后。


23
投票

从活动使用中启动和停止前台服务:

//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);
        stopSelf();
    }
    return START_STICKY;
}

1
投票

除了其他答案,我用这个片段结束使用android oreo和laters来停止工作服务。

Intent intent = new Intent(getApplicationContext(), LocationService.class);
intent.setAction(status);
ContextCompat.startForegroundService(getApplicationContext(), intent);

并在服务中

@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
  startForeground(121, notification);
  if (intent.getAction().equals("StopService")) {
    stopForeground(true);
    stopSelf();
  }

startForeground()是强制性的,除非app在没有调用它的情况下崩溃

新的Context.startForegroundService()方法启动前台服务。即使应用程序在后台,系统也允许应用程序调用Context.startForegroundService()。但是,应用程序必须在创建服务后的五秒内调用该服务的startForeground()方法。

https://developer.android.com/about/versions/oreo/android-8.0-changes.html


0
投票

如上所述:https://developer.android.com/guide/components/services#Stopping

已启动的服务必须管理自己的生命周期。也就是说,系统不会停止或销毁服务,除非它必须恢复系统内存并且服务在onStartCommand()返回后继续运行。服务必须通过调用stopSelf()来自行停止,或者另一个组件可以通过调用stopService()来停止它。

一旦请求使用stopSelf()或stopService()停止,系统将尽快销毁服务。

因此,您可以从用于调用startService()的活动中调用stopService()。我在这里做到了:

start_button.setOnClickListener {
        applicationContext.startForegroundService(Intent(this, ServiceTest::class.java))
    }
    stop_button.setOnClickListener {
        applicationContext.stopService(Intent(this, ServiceTest::class.java))
    }

我创建了两个按钮来启动和停止服务,它的工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.