【问题标题】:how to stop the update of the widget android when I turn off the screen?关闭屏幕时如何停止小部件android的更新?
【发布时间】:2015-03-04 18:05:29
【问题描述】:

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

【问题讨论】:

    标签: android widget alarmmanager powermanager


    【解决方案1】:

    当你触发警报时,只检查屏幕是否亮着怎么样?

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 谢谢,但我无法实现,因为我在类 WidgetProvider
      猜你喜欢
      • 2022-01-01
      • 2023-03-12
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多