[英]Service stops running after closing the app
我在Android寫了一個簡單的服務,只要app運行就運行,應用關閉就停止。 我的代碼如下:
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
當一個應用程序在前台時,它可以自由地創建和運行前台和后台服務。 當一個應用程序進入后台時,它有幾分鍾的時間 window,在此期間它仍然可以創建和使用服務。 在 window 結束時,應用程序被認為是空閑的。 此時系統會停止應用的后台服務,就像應用調用了服務的 Service.stopSelf() 方法一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.