java 关闭时_java – 活动关闭时服务停止
我已經(jīng)閱讀了一些與這個問題相關的答案,它們似乎都是一樣的:
“使用START_STICKY運行您的服務”
“在前臺運行您的服務”
“使用startService運行您的服務,不要綁定它”
我正在做所有這些事情,我的服務STILL關閉并在每次關閉活動時重新啟動.
這不是IntentService.
我也沒有在onClick處理程序中調(diào)用stopSelf或stopService.
請向下滾動到我的更新 – 此行為已被確認為Android操作系統(tǒng)中的錯誤,我已將其報告給谷歌. Click here to view the report.
從MainActivity啟動我的服務:
svcIntent = new Intent(getBaseContext(), MyService.class);
startService(svcIntent);
在我的onStartCommand中:
// Enter foreground state
String title = "Service has been started...";
String subject = "Service is running...";
String body = "Monitoring your battery usage.";
Notification notification = new Notification(R.drawable.theicon, title,
System.currentTimeMillis());
if (prefs.getBoolean("notificationSounds", true))
notification.defaults |= Notification.DEFAULT_SOUND;
else
notification.sound = null;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, subject, body, pendIntent);
startForeground(1500, notification);
在我的onStartCommand結束時:
...
// Release WakeLock
wl.release();
return START_STICKY;
UPDATE
我想出了什么導致它!但我不知道如何解決它.在我的服務中,我還使用服務中的AlarmManager在指定的時間內(nèi)設置對服務的函數(shù)調(diào)用.
// Alarm manager setup for MyService
AlarmManager AM = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
svcIntent1 = new Intent(this, AlarmReceiver.class);
prefs.edit().putInt("initialBatt", initialBatt).apply();
svcIntent1.setAction("com.myApp.servicealarm");
pendingIntent = PendingIntent.getBroadcast(this, 93, svcIntent1, PendingIntent.FLAG_UPDATE_CURRENT);
// Set the alarm
AM.set(AlarmManager.RTC_WAKEUP, timeNow + waitTime, pendingIntent);
我注意到如果我不注釋AM.set調(diào)用來設置警報,即使有一個EMPTY onReceive,我的服務在鬧鐘響起時被殺死,在我最近的應用程序中刷掉我的應用程序之后.如果我注釋掉設置的警報調(diào)用,那么在關閉我的應用程序后,服務永遠不會被殺死并繼續(xù)運行.有沒有搞錯?!我的算法功能需要這個警報!
這很奇怪.一旦鬧鐘響起,我的調(diào)試消息就不會打印,我的服務會重新啟動.但第二次,在服務重新啟動后,調(diào)試消息會打印并且程序成功執(zhí)行.
我已經(jīng)嘗試了這個,它仍然發(fā)生在普通的廣播接收器上.我還將我的代碼剝離到我的服務和廣播接收器的設置警報調(diào)用,同樣的事情發(fā)生,所以這不是我的算法.顯然,如果您有一個設置鬧鐘的前臺服務,當鬧鐘響起時,您的服務將重新啟動.
閉幕
這種行為似乎是由Android操作系統(tǒng)中的一個錯誤引起的,所以我不希望得到答案.如果你想自己看看這個bug,click here.我提供了一個你可以編譯并重現(xiàn)問題的項目.
總結
以上是生活随笔為你收集整理的java 关闭时_java – 活动关闭时服务停止的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL调用存储过程和函数
- 下一篇: 【JAVA】-- 坦克大战全部代码