[英]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.