继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