简体   繁体   中英

how to stop the update of the widget android when I turn off the screen?

i'm creating an application with widget. The widget is updated every 10 seconds through AlarmManager, but I would that the AlarmManager stops when the screen is off, to prevent a possible battery drain. How can I do? I tried using PowerManager but without success. I have implemented the AlarmManager in WidgetProvider, and through broadcast calls the class WidgetReceiver, which updates the values

-WIDGET PROVIDER:

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
}

How about just checking whether the screen is on when you trigger the alarm?

PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn()) {
    // schedule the alarm
}

Something along the lines of this will turn off your alarm when the screen's off:

@Override
protected void onPause() {
    super.onPause();
    // If the alarm has been set, cancel it.
    if (alarmMgr!= null) {
        alarmMgr.cancel(alarmIntent);
    }
}

If you want it to start up again when the screen turns back on, you'll need to add corresponding code in onResume.

EDIT

Whoops, this will turn off your alarm whenever the activity was paused. Better would be to combine this with the other answer like so:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM