0

我正在创建一个带有小部件的应用程序。该小部件通过 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;
}

-小部件接收器:

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
}
4

2 回答 2

1

触发警报时仅检查屏幕是否亮如何?

PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn()) {
    // schedule the alarm
}
于 2015-03-04T03:45:33.137 回答
0

当屏幕关闭时,类似的东西会关闭你的闹钟:

@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);
    }
}
于 2015-03-04T03:46:07.130 回答