Background process timer on android

前端 未结 2 670
星月不相逢
星月不相逢 2021-01-03 06:19

I\'m trying to get a process timer to run and keep it running in the background on android (starts with a button click).

The timer must be on 30 seconds and should e

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 07:15

    Ok, first of all, I really don't know if I got your question quite right. But I think you want a timer that's being executed every 30 seconds ,if i'm not mistaken. If so, do as following:

    AlarmManager

    Note: This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

    Example:

    in your onClick() register your timer:

    int repeatTime = 30;  //Repeat alarm time in seconds
    AlarmManager processTimer = (AlarmManager)getSystemService(ALARM_SERVICE);
    Intent intent = new Intent(this, processTimerReceiver.class);   
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  intent, PendingIntent.FLAG_UPDATE_CURRENT);
    //Repeat alarm every second
    processTimer.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),repeatTime*1000, pendingIntent); 
    

    And your processTimerReceiver class:

    //This is called every second (depends on repeatTime)
    public class processTimerReceiver extends BroadcastReceiver{
    
        @Override
        public void onReceive(Context context, Intent intent) {
            //Do something every 30 seconds
        }
    }
    

    Don't forget to register your receiver in your Manifest.XML

    
       
           
           
       
    
    

    If you ever want to cancel the alarm: use this to do so:

    //Cancel the alarm
    Intent intent = new Intent(this, processTimerReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);
    

    Hope this helps you out.

    PS: if this is not exactly what u want, please leave it in the comments, or if someone wants to edit this, please do so.

提交回复
热议问题