[英]how to stop the update of the widget android when I turn off the screen?
我正在使用小部件创建应用程序。 该小部件通过AlarmManager每10秒更新一次,但我希望在屏幕关闭时AlarmManager停止,以防止可能的电池消耗。 我能怎么做? 我尝试使用PowerManager,但没有成功。 我已经在WidgetProvider中实现了AlarmManager,并通过广播调用WidgetReceiver类,该类更新了值
-小工具提供者:
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC,
System.currentTimeMillis() + 1000, 1000 * 5, update(context));
}
public static PendingIntent update(Context context) {
Intent intent = new Intent();
intent.setAction("com.aaa.intent.action.UPDATE_TIME");
if (service == null) {
service = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
return service;
}
-WIDGET RECEIVER:
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.gabriele.intent.action.UPDATE_TIME")) {
updateWidget(context);
}
}
private void updateWidget(Context context) {
update my widget
}
如何在触发警报时仅检查屏幕是否打开?
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn()) {
// schedule the alarm
}
当屏幕关闭时,类似的事情将关闭您的警报:
@Override
protected void onPause() {
super.onPause();
// If the alarm has been set, cancel it.
if (alarmMgr!= null) {
alarmMgr.cancel(alarmIntent);
}
}
如果您希望它在屏幕重新打开时再次启动,则需要在onResume中添加相应的代码。
编辑
糟糕,每当活动暂停时,这就会关闭您的警报。 最好将其与其他答案结合起来,如下所示:
PowerManager pm;
@Override
protected void onPause() {
super.onPause();
if (pm==null) {
pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
}
// If the alarm has been set AND the screen is off
if (alarmMgr!= null && !pm.isScreenOn()) {
alarmMgr.cancel(alarmIntent);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.