启动重复警报,仅当 运行 尚未完成时才执行后台服务

Start a repeating alarm that performs a background service only if it isn't running already

我有一个在 MainActivity 的 onCreate() 方法中启动的警报。它执行后台服务,每 20 分钟从 Internet 定期获取数据。它工作正常。但问题是,每次用户退出应用再打开,都会重新设置闹钟并启动后台服务。因此,有多个警报 运行ning 并且服务 运行 是随机间隔的。如何仅在没有 运行ning 的情况下启动闹钟?我在互联网上搜索并找到了一个名为 PendingIntent.FLAG_NO_CREATE 的东西,但我似乎无法正确使用它。任何帮助,将不胜感激。这是我在 onCreate() 方法中的警报代码。

/**** CODE FOR BACKGROUND SERVICE ****/

    Intent alarm = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarm, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating
                (AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1200000, pendingIntent);


    /**** END CODE FOR BACKGROUND SERVICE ****/

是的,您需要使用 PendingIntent.FLAG_NO_CREATE。你试过这样实现吗?

/**** CODE FOR BACKGROUND SERVICE ****/

    Intent alarm = new Intent(this, AlarmReceiver.class);
    // Check if the alarm receiver is currently active
    boolean alarmRunning = (PendingIntent.getBroadcast(this, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
    if(alarmRunning == false) {
        // Alarm is not running. Set it up
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarm, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating
                (AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1200000, pendingIntent);
    }
    else {
        // Alarm is running..
        Log.d("ALARM TAG", "Alarm is already running. Do nothing.");
    }

    /**** END CODE FOR BACKGROUND SERVICE ****/