手机睡眠时Android AlarmManager无法正常工作

时间:2016-11-30 20:00:37

标签: android alarmmanager sony wakelock sleep-mode

我遇到了AlarmManager的问题。

简而言之,我计划一个alarmManager:

Intent intent = new Intent(context, MyActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delayInMs, pendingIntent);

活动MyActivity在指定时间出现。就在插入设备时。当它放在我的口袋里,或延迟几分钟时,它也可以工作。 但是当我在夜间设置alarmManager时,它在早上不能工作。但是,一旦我拿起电话或解锁屏幕,它就会起作用。

所以,我想这是由于设备的睡眠模式,但是如何解决这个问题?

1)我在myActivity的每个方法中添加了一个日志,并且在手动唤醒设备之前我确定没有人被调用。 2)我尝试了PowerManagement的唤醒锁定(清单中的WAKE_LOCK权限),但没有改变:

alarmManager.setExact(.........);
wakeLock = ((PowerManager)contexte.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "MyActivity");
wakeLock.acquire();

请帮忙!我确定我这么近......

编辑12月04日' 16: 感谢Nick Friskel和Vikram Rao,我更改了我的初始代码以调用broadcastReceiver并在onReceive中获取wakeLock。不幸的是,它似乎不起作用。当手机插上电源或35分钟后计划完警报时,它可以完美地工作,但是对于整晚来说,onReceive甚至不会被呼叫。 那天晚上我尝试了闹钟,计划在上午9点发出警报,但onReceive仅在上午9:46执行,这意味着我解锁设备的那一刻。 这是我的新代码:

Intent intent = new Intent("com.blah.something.ALARM_RECEIVED");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delayInMs, pendingIntent);

那就是说,我的日志写作"开始onReceive"由于某种原因,听众并没有真正开始。我只是设法把它放在真正的开头,所以我会看看听众是否被调用。

编辑12月05日' 16: 所以,我在onReceive的顶部更改了日志写入,并且发生了同样的问题:一旦我手动唤醒设备,就会调用onReceive的开始。 我可以实现wakefulBroadcastReceiver,但我担心它不会解决任何问题。如果我理解正确,wakefulBroadcastReceiver可以防止设备在onReceive和活动或服务的启动之间休眠。但是如果onReceive甚至不被称为怎么办呢? 我有点绝望......也许我应该直接问索尼。 此外,我的手机具有耐力模式,但它没有被激活。

编辑12月11日' 16: 所以,通过更多测试,我现在确定我什么都不懂......我设置了一个每5分钟激活一次的broadcastReceiver(onReceive会在5分钟后重置alarmManager),我可以看到它完美的工作...有时候。它可以持续几个小时,然后睡两个小时,然后可以睡30分钟,然后再回到睡眠状态。 (当我的手机开机,拔掉电源并闲置时)。 我将删除所有代码但我们感兴趣的是什么。它将更容易理解,我将能够在这里写下所有活动代码。

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.par.hasard.mysimpleapplication">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="com.par.hasard.mysimpleapplication.MySimpleReceiver">
            <intent-filter android:priority="1">
                <action android:name="com.par.hasard.mysimpleapplication.REGULAR_ALARM" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

MainActivity.java

package com.par.hasard.mysimpleapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.myExportButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyLogManager.copyLogToClipboard(view.getContext());
                MyLogManager.emptyLogFile(view.getContext());
            }
        });
        try {
            MyLogManager.createLogFile(this);
            MyLogManager.write(this, "Application launched\n");
            MyAlarmPlanner.planAlarm(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

MySimpleReceiver.java

package com.par.hasard.mysimpleapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MySimpleReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            MyLogManager.write(context, "Beginning of onReceive\n");
            MyAlarmPlanner.planAlarm(context);
            MyLogManager.write(context, "End of onReceive\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

MyAlarmPlanner.java

package com.par.hasard.mysimpleapplication;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import java.io.IOException;

public class MyAlarmPlanner {
    public static void planAlarm(Context context) throws IOException {
        MyLogManager.write(context, "Beginning of alarm planning\n");
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent("com.par.hasard.mysimpleapplication.REGULAR_ALARM");
        PendingIntent pendingIntent =  PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.cancel(pendingIntent);
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 300000, pendingIntent);
        MyLogManager.write(context, "End of alarm planning\n");
    }
}

我不认为MyLogManager.java很有用,它只是无聊的文件管理方法。

长时间闲置后的日志文件内容:

12/12 15h33m23s380 => Beginning of onReceive
12/12 15h33m23s381 => Beginning of alarm planning
12/12 15h33m23s383 => End of alarm planning
12/12 15h33m23s384 => End of onReceive
12/12 15h38m24s337 => Beginning of onReceive
12/12 15h38m24s339 => Beginning of alarm planning
12/12 15h38m24s375 => End of alarm planning
12/12 15h38m24s376 => End of onReceive
12/12 15h43m24s375 => Beginning of onReceive
12/12 15h43m24s376 => Beginning of alarm planning
12/12 15h43m24s380 => End of alarm planning
12/12 15h43m24s381 => End of onReceive
12/12 15h48m25s301 => Beginning of onReceive
12/12 15h48m25s304 => Beginning of alarm planning
12/12 15h48m25s307 => End of alarm planning
12/12 15h48m25s308 => End of onReceive
12/12 15h53m25s316 => Beginning of onReceive
12/12 15h53m25s318 => Beginning of alarm planning
12/12 15h53m25s328 => End of alarm planning
12/12 15h53m25s329 => End of onReceive
12/12 15h58m25s328 => Beginning of onReceive
12/12 15h58m25s329 => Beginning of alarm planning
12/12 15h58m25s331 => End of alarm planning
12/12 15h58m25s333 => End of onReceive
12/12 16h3m26s336 => Beginning of onReceive
12/12 16h3m26s351 => Beginning of alarm planning
12/12 16h3m26s379 => End of alarm planning
12/12 16h3m26s380 => End of onReceive
12/12 16h8m26s397 => Beginning of onReceive
12/12 16h8m26s401 => Beginning of alarm planning
12/12 16h8m26s404 => End of alarm planning
12/12 16h8m26s405 => End of onReceive
12/12 16h13m26s406 => Beginning of onReceive
12/12 16h13m26s407 => Beginning of alarm planning
12/12 16h13m26s410 => End of alarm planning
12/12 16h13m26s411 => End of onReceive
12/12 16h18m27s328 => Beginning of onReceive
12/12 16h18m27s329 => Beginning of alarm planning
12/12 16h18m27s346 => End of alarm planning
12/12 16h18m27s348 => End of onReceive
12/12 16h23m28s298 => Beginning of onReceive
12/12 16h23m28s299 => Beginning of alarm planning
12/12 16h23m28s303 => End of alarm planning
12/12 16h23m28s304 => End of onReceive
12/12 16h28m29s308 => Beginning of onReceive
12/12 16h28m29s310 => Beginning of alarm planning
12/12 16h28m29s323 => End of alarm planning
12/12 16h28m29s324 => End of onReceive
12/12 16h33m29s339 => Beginning of onReceive
12/12 16h33m29s340 => Beginning of alarm planning
12/12 16h33m29s355 => End of alarm planning
12/12 16h33m29s361 => End of onReceive
12/12 16h38m29s356 => Beginning of onReceive
12/12 16h38m29s357 => Beginning of alarm planning
12/12 16h38m29s360 => End of alarm planning
12/12 16h38m29s361 => End of onReceive
12/12 16h43m29s364 => Beginning of onReceive
12/12 16h43m29s365 => Beginning of alarm planning
12/12 16h43m29s367 => End of alarm planning
12/12 16h43m29s369 => End of onReceive
12/12 16h48m29s376 => Beginning of onReceive
12/12 16h48m29s380 => Beginning of alarm planning
12/12 16h48m29s390 => End of alarm planning
12/12 16h48m29s394 => End of onReceive
12/12 16h53m29s392 => Beginning of onReceive
12/12 16h53m29s394 => Beginning of alarm planning
12/12 16h53m29s402 => End of alarm planning
12/12 16h53m29s403 => End of onReceive
12/12 17h43m33s986 => Beginning of onReceive      //problem, the 16'58 onReceive wasn't called
12/12 17h43m33s988 => Beginning of alarm planning
12/12 17h43m33s996 => End of alarm planning
12/12 17h43m34s4 => End of onReceive
12/12 17h48m34s535 => Beginning of onReceive
12/12 17h48m34s536 => Beginning of alarm planning
12/12 17h48m34s539 => End of alarm planning
12/12 17h48m34s540 => End of onReceive
12/12 18h29m49s635 => Beginning of onReceive     //the moment I turned on my device
12/12 18h29m49s648 => Beginning of alarm planning
12/12 18h29m49s667 => End of alarm planning
12/12 18h29m49s668 => End of onReceive

有人能告诉我我的错误在哪里吗?

3 个答案:

答案 0 :(得分:5)

感谢CommonsWare,问题解决了!此失败是由于打盹模式(https://developer.android.com/training/monitoring-device-state/doze-standby.html) 简而言之,自Android 6.0起,AlarmManager受到影响,如果设备处于此打盹模式,则无法触发。但是你可以用setExactAndAllowWhileIdle替换setExact。有一些限制,但我们必须处理。有CommonsWare回答的帖子的链接: sendWakefulWork not always called with cwac-wakeful-1.1.0

答案 1 :(得分:1)

android中的AlarmManager api有其局限性。对于 -

  1. 重启设备时清除它(所有警报丢失)
  2. 在设备锁定/睡眠状态期间,它在制造商和Android版本之间的行为不一致
  3. 我解决这些问题的方法是 -

    1. 创建具有广播意图的警报,然后将侦听器添加到该广播以执行必要的操作。
    2. 喜欢这个 -

      Intent intent = new Intent("com.blah.something.ALARM_RECIEVED");
      PendingIntent pendingIntent =  PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
      AlarmManager alarmManager = (AlarmManager) context.getSystemService(Html5Activity.ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, triggerTimeInMillis, pendingIntent);
      

      清单文件 -

      <receiver android:name=".receiver.BackgroundScheduledAlarmReceiver">
           <intent-filter android:priority="1">
                <action android:name="com.blah.something.ALARM_RECIEVED" />
           </intent-filter>
      </receiver>
      
      1. 在sqlite或其他地方保存警报(此处未显示),并在设备重新启动时通过监听设备启动重新创建警报 -
      2. 清单文件 -

        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        ...
        <receiver
            android:name=".receiver.RecreateAlarmsAtBootReceiver"
            android:enabled="true"
            android:exported="true"
            android:label="RecreateAlarmsAtBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>
        

        RecreateAlarmsAtBootReceiver中,阅读sqlite存储警报并再次将它们添加到警报管理器。

答案 2 :(得分:0)

执行此操作的正确方法是让AlarmManager触发BroadcastReceiver而不是直接Activity。然后,您可以将您的唤醒锁放在广播接收器类中,然后从BroadcastReceiver或从BroadcastReceiver启动的IntentService运行您的活动。

您的意图将更改为:

Intent intent = new Intent(context, MyActivityReceiver.class);

然后制作你的广播接收器:

package com.yourpackage (change this to your package)

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyActivityReceiver extends BroadcastReceiver {
    public static final int REQUEST_CODE = 0; //only necessary if you have more receivers 

    // when the alarm is triggered
    @Override
    public void onReceive(Context context, Intent intent) {
    wakeLock = ((PowerManager)contexte.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "MyActivity");
    wakeLock.acquire();
    Intent i = new Intent(context, MyActivity.class);
    context.startService(i);
    }
}

并将接收器添加到您的Manifest:

<receiver
            android:name="service.TimeService"
            android:enabled="true"
            android:exported="false"
            >
</receiver>

如果这不起作用,那么您需要通过WakefulService开始活动。