繼docs之後,我設法使用AlarmManager設置鬧鐘,一旦我不關閉手機屏幕,鬧鐘就會很好地工作。AlarmManager:當屏幕關閉時,等待的意圖消失
這是adb shell dumpsys alarm
輸出時屏幕上:
Batch{1304da7 num=1 start=190708622 end=190708622 flgs=0x1}:
RTC_WAKEUP #0: Alarm{f642254 type 0 when 1480059825231 alarm.poc.app}
tag=*walarm*:alarm.poc.app.ACTION
type=0 whenElapsed=+5m49s424ms when=2016-11-25 02:43:45
window=0 repeatInterval=0 count=0 flags=0x1
operation=PendingIntent{f78d3a6: PendingIntentRecord{f52e1e7 alarm.poc.app broadcastIntent}}
幾秒鐘後,我關閉屏幕我的鬧鐘從命令輸出消失,不會被調用(它的工作原理與屏幕上)。
所以,我有以下問題:
- 什麼其他的應用程序做的,讓報警活着嗎?我可以在
adb shell dumpsys alarm
的輸出中看到,即使我清除了所有最近的應用程序,也有大量的其他鬧鐘未被刪除。我可以看到WhatsApp,Google和其他許多隨機應用的警報。 - 也許所有這些應用程序都有前臺服務?我問這個是因爲我設法「解決」了創建一個令人討厭的前景服務的問題,該服務每5秒向日志中寫入一些內容。它看起來像一個正在運行的服務可以防止問題,但它是完全醜陋的,我認爲保持處理器始終保持清醒並不是一個好主意。
這是我如何設置報警:
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(AlarmReceiver.MY_ACTION);
intent.putExtra("text", editText.getText().toString());
PendingIntent pending = PendingIntent.getBroadcast(this, 42,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// also tried with getBroadcast(this, 0, intent, 0)
manager.setExact(AlarmManager.RTC_WAKEUP, millis, pending);
我有一個WakefulBroadcastReceiver(不調用屏幕關閉):
public void onReceive(Context context, Intent receivedIntent) {
if (MY_ACTION.equals(receivedIntent.getAction())) {
System.out.println("good!!!");
String text = receivedIntent.getStringExtra("text");
Intent intentService = new Intent(context, TestService.class);
intentService.putExtra("text", text);
startWakefulService(context, intentService);
System.out.println("service started");
}
}
而且清單:
...
<uses-permission android:name="android.permission.WAKE_LOCK"/>
...
<service android:name="alarm.poc.app.TestService"
android:exported="false"/>
<receiver android:name="alarm.poc.app.AlarmReceiver"
android:process=":remote">
<intent-filter>
<action android:name="alarm.poc.app.ACTION"/>
</intent-filter>
</receiver>
...
我正在棉花糖手機上測試minSdkVersion 19和targetSdkVe rsion 24