How to check if Alarm have been set and running

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

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


            
                       


        
相关标签:
2条回答
  • 2021-01-06 15:52

    The only thing you can do is when the user install the app and open it the first time you can set a flag in the SharedPreference that tells you if the Alarm is set or not if its not set set the Alaram .

    in your main Activity check in the onCreate method

    SharedPreferences spref = getSharedPreferences("TAG", MODE_PRIVATE);
    
     Boolean   alaram_set = spref.getBoolean("alarm_set_flag", false);  //default is false
    
    if(!alaram_set){
    //create your alarm here then set the flag to true
    
     SharedPreferences.Editor editor = spref.edit();
            editor.putBoolean("alarm_set_flag", true); // value to store
            editor.commit();
    }
    
    0 讨论(0)
  • 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?

    0 讨论(0)
提交回复
热议问题