How to check if Alarm have been set and running

前端 未结 2 1685
青春惊慌失措
青春惊慌失措 2021-01-06 15:17

I have a receiver that start after phone boot like this:


            
                       


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-06 15:55

    Sadly, you cant query AlarmManager for current Alarms.

    Best option to solve your problem would be to cancel your current Alarm and set a new one.

    You just have to create an intent that matches the one in the reciever. More info here

    so add this to your activity

       AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    
         Intent i=new Intent(context, LocationPoller.class);
    
            i.putExtra(LocationPoller.EXTRA_INTENT,
                      new Intent(context, LocationReceiver.class));
            i.putExtra(LocationPoller.EXTRA_PROVIDER,
                     LocationManager.GPS_PROVIDER);
    
            PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
        // Cancel alarms
        try {
            AlarmManager.cancel(pi);
        } catch (Exception e) {
            Log.e(TAG, "AlarmManager update was not canceled. " + e.toString());
        }
    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                            SystemClock.elapsedRealtime(),
                            PERIOD,
                            pi);
    

    You probably need to change the context of the intent so its the same as the one in the Reciever.

    Another Workaround would be to detect if its the first start of the App, and only start it then. But then what happens if user reboots his phone before the first start?

提交回复
热议问题