只有在尚未运行后才开始执行后台服务的重复警报

时间:2015-05-30 14:01:19

标签: android alarm

我有一个在MainActivity的onCreate()方法内启动的警报。它执行后台服务,每20分钟定期从互联网上获取数据。它工作正常。但问题是,每次用户退出应用程序并再次打开它时,将再次设置警报并启动后台服务。因此,有多个警报在运行,服务以随机间隔运行。如果一个人还没有跑步,我该如何启动闹钟?我在互联网上搜索了一些名为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 ****/

1 个答案:

答案 0 :(得分:1)

是的,您需要使用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 ****/