AlarmManager - 设置为10分钟后不会熄灭

时间:2015-01-13 00:33:28

标签: java android android-intent alarmmanager android-intentservice

基本上这个代码是如何工作的......它从初始计算开始,并在X分钟后用一个告警管理器启动一个服务,得到一个结束计算并确定两者之间的差异。在每个警报结束时,将在相同的时间间隔内设置新警报。当我将时间间隔设置为10分钟时,警报根本不会响起。

我认为这与手机CPU进入睡眠状态有关,因为这是我多年来一直试图解决的问题,有很多不同的方法来编写这种算法。

如果有人知道为什么会这样,那么任何帮助都会非常感激,因为这对我的程序的功能非常重要。作为旁注,这段代码在短时间内运行完美无缺,最长可达5分钟,一旦插入10,我就什么都没有。

从我的服务

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    // Set return value
    int retVal = START_NOT_STICKY;

    if (intent != null) {

        System.out.println("Service Thread: " + Thread.currentThread().getName());

        // Set up context reference for getObject
        self = this;

        // Set up global intent reference
        theIntent = intent;

        // Get data
        getData();

        // Enter foreground state
        String title = "The service has been started...";
        String subject = "Service is running.";
        String body = "Monitoring your battery usage...";
        Notification notification = new Notification(R.drawable.theicon, title,
                System.currentTimeMillis());
        if (notificationSounds)
            notification.defaults |= Notification.DEFAULT_SOUND;
        else
            notification.sound = null;
        Intent notificationIntent = new Intent(this, MainActivity3.class);
        PendingIntent pendIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, subject, body, pendIntent);
        startForeground(1500, notification);

        // Calculate wait time (convert from minutes to ms)
        int waitTime = interval * 60000;
       // int waitTime = 15000; // Debug 15 second wait

        // Get initial battery
        int initialBatt = getBatteryPercent();

        // Debug
        System.out.println("Initial battery percent: " + initialBatt);

        // Get current time
        Calendar c = Calendar.getInstance();
        Date dateNow = c.getTime();
        long timeNow = dateNow.getTime(); // Time in MS

        // Set up alarm manager to wait and then execute next step
        AlarmManager AM = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        svcIntent1 = new Intent(Service.getObject(), AlarmReceiver.class);
        svcIntent1.putExtra("timeToUse", timeToUse);
        svcIntent1.putExtra("interval", interval);
        svcIntent1.putExtra("rawTime", rawTime);
        svcIntent1.putExtra("initialBatt", initialBatt);
        svcIntent1.putExtra("sounds", notificationSounds);
        pendingIntent = PendingIntent.getBroadcast(Service.getObject(), 0, svcIntent1, PendingIntent.FLAG_UPDATE_CURRENT);

        // Set up the next alarm
        System.out.println("The current time is " + dateNow.
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd hh:mm:ss a");
        Toast.makeText(this, "The current time is " + sdf.format(dateNow), Toast.LENGTH_LONG).show();
        Date n = new Date();
        n.setTime(timeNow+waitTime);
        System.out.println("Next calculation will complete at " + sdf.format(n));
        Toast.makeText(this, "Next calculation will complete at " + sdf.format(n), Toast.LENGTH_LONG).show();
        AM.setExact(AlarmManager.RTC_WAKEUP, timeNow + waitTime, pendingIntent);
    }
    return retVal;
}

onReceive在我的广播接收器类

@Override
public void onReceive(Context c, Intent intent) {
    if(intent != null){
        // Get app context
        context = Service.getObject();

        Toast.makeText(context, "Alarm broadcast received.", Toast.LENGTH_SHORT).show();

        // Set up the intent
        theIntent = intent;

        // Get the extra data
        getData();

        // Do calculations and get new initial battery level for next alarm
        int endBatt = calculateHelper(initialBatt);

        // Set up alarm manager to wait and then execute next step
        AlarmManager AM = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent svcIntent1 = new Intent(Service.getObject(), AlarmReceiver.class);
        svcIntent1.putExtra("timeToUse", timeToUse);
        svcIntent1.putExtra("interval", interval);
        svcIntent1.putExtra("rawTime", rawTime);
        svcIntent1.putExtra("initialBatt", endBatt);
        svcIntent1.putExtra("sounds", context.notificationSounds);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(Service.getObject(), 0, svcIntent1, PendingIntent.FLAG_UPDATE_CURRENT);

        // Get times
        long timeNow = dateNow.getTime();
        int waitTime = interval * 60000;


        // Debug stuff
        // int waitTime = 15000;
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd hh:mm:ss a");
        System.out.println("The current time is " + sdf.format(dateNow));
        Toast.makeText(context, "The current time is " + sdf.format(dateNow), Toast.LENGTH_LONG).show();
        Date n = new Date();
        n.setTime(timeNow+waitTime);
        System.out.println("Next calculation will complete at " + sdf.format(n));
        Toast.makeText(context, "Next calculation will complete at " + sdf.format(n), Toast.LENGTH_LONG).show();

        // Setting the next alarm
        AM.setExact(AlarmManager.RTC_WAKEUP, timeNow + waitTime, pendingIntent);
    }
    else
        notify0(10,"ERROR", "ERROR", "Intent is null", true);
}

在我的清单中......

    <receiver
        android:name=".AlarmReceiver"
        android:enabled="true"
        android:exported="true" >
    </receiver>

<小时/>

我的新代码(感谢Larry Schiefer的建议)

我还发现,即使WakefulBroadcastReceiver持有WakeLock,如果操作系统要关闭服务,它也会在没有WakeLock的情况下重新启动。因此,有时需要在onStartCommand中获取额外的唤醒锁以进行处理。就我而言,这是必需的。

在我的服务中

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    // Acquire WakeLock
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Service WakeLock");
    wl.acquire();

    // Set up global intent reference
    theIntent = intent;

    if (theIntent != null) {
        getData();
        if (intent.getAction().equals("Start_Interval")) {
            doStart();
        }
        else if(intent.getAction().equals("End_Interval")){
            doEnd();
        }
    }
    else{
        Log.e("ERROR", "The intent is NULL inside of onStartCommand. Activity closed?");
        cancelAlarm();
        stopSelf();
    }

    // Release WakeLock
    wl.release();

    return START_STICKY;
}

我的onReceive - Changed“将BroadcastReceiver扩展为”扩展WakefulBroadcastReceiver“

@Override
public void onReceive(Context c, Intent intent) {
    if(intent != null){

        // Debug
        Log.d("Debug","Alarm broadcast received.");

        // Set up the global intent reference
        theIntent = intent;

        // Set up service context reference
        context = Service.getObject();

        // Get data from the intent
        getData();

        // Set up the new intent
        Log.d("Debug", "Setting up new intent with context: " + c + " and class: " + Service.class);
        Intent service = new Intent(c, Service.class);
        service.putExtra("timeToUse", timeToUse);
        service.putExtra("interval", interval);
        service.putExtra("rawTime", rawTime);
        service.putExtra("initialBatt", initialBatt);
        service.setAction("End_Interval");

        // Wake up the service and complete this interval's calculations
         startWakefulService(c, service);
    }
    else {
        context.cancelAlarm();
        context.stopSelf();
    }
}

1 个答案:

答案 0 :(得分:0)

Log中使用Toast而非BroadcastReceiver来验证是否已收到广播。一旦系统进入低功耗状态,RTC_WAKEUP将唤醒它,但仅在你的onReceive正在执行时才唤醒它。在此之后,系统将释放其唤醒锁以进行警报,系统可以在屏幕显示之前返回睡眠状态。如果您需要服务根据警报实际执行某些操作,则需要使用自己的唤醒锁来协调接收器和服务,以确保系统保持正常运行(请参阅WakefulBroadcastReceiver。)