关闭应用程序后服务停止 运行

Service stops running after closing the app

我在Android写了一个简单的服务。它 运行 只要应用程序是 运行 并在应用程序关闭时停止。我的代码如下:

public class WitoService extends Service {
private MediaPlayer mp;
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //return super.onStartCommand(intent, flags, startId);
    mp=MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
    mp.setLooping(true);
    mp.start();
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    mp.stop();
}

}

清单文件条目

<service android:name=".WitoService"/>

服务调用代码:

if(!serviceRunning) {
        startService(new Intent(this, WitoService.class));
        serviceRunning=true;
    }else {
        stopService(new Intent(this, WitoService.class));
        serviceRunning=false;
    }

enter code here

当您的应用程序目标大于 android O 时,这是正常行为。要保持您的服务有效,应创建前台服务并通过通知通知用户。你可以在这里查看 https://developer.android.com/about/versions/oreo/background#services

While an app is in the foreground, it can create and run both foreground and background services freely. When an app goes into the background, it has a window of several minutes in which it is still allowed to create and use services. At the end of that window, the app is considered to be idle. At this time, the system stops the app's background services, just as if the app had called the services' Service.stopSelf() methods.