javaandroidalarmmanageralarmrepeatingalarm

can i change an alarn to a repeating alarm?



how can i change an allreaddy set alarm to a repeating alarm? i set the alarm with the AlarmManager? My actual code looks like this:

    intent = new Intent(MainActivity.this, AlarmReceiverActivity.class);
                        pendingIntent = PendingIntent.getActivity(MainActivity.this, 2, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, time, intervall, pendingIntent);

thanks for helping,
Florian

edit: i solved my problem in a other way(setting a new alarm every time), so no stress, but i am stil wondering how this would work


Solution

  • You have done this job by Service class.

    For example

    In the Application's onCreate() method, you have to initialize the AlarmManager like below.

    long l = 60000;
    try {
    
                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    
                Intent intent = new Intent(context, SyncBroadcastReceiver.class);
    
                PendingIntent pendingIntent = PendingIntent.getBroadcast(context, SYNC_CALL_TO_SERVER_PENDING_INTENT,
                        intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
                alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), l, pendingIntent);
    
            }catch (Exception e){
                e.printStackTrace();
    
            }
    

    And SyncBroadcastReceiver like,

    public class SyncBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                //comment to check crash
                Intent intent1 = new Intent(context, ServiceClass.class);
    
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(intent1);
                } else {
                    context.startService(intent1);
                }
            } catch (Exception e){
                e.printStackTrace();
    
            }
        }
    }
    

    And ServiceClass like

    public class ServiceClass extends Service {
         @Override
         public int onStartCommand(Intent intent, int flags, int startId) {
             // hitNotification(); // what need to act like notification dialog
             return START_NOT_STICKY;
        }
    }