Android execute a function after 1 hour

前端 未结 3 532
太阳男子
太阳男子 2020-12-19 16:09

I have an android application where I am storing user\'s data on database when he/she activates the app. My app requires the user to stop the application manually in order t

相关标签:
3条回答
  • 2020-12-19 16:48

    Use AlarmManager refer this and tutorial with PendingIntent

    0 讨论(0)
  • 2020-12-19 16:52

    I suggest the code will be like this.

    // the scheduler
    protected FunctionEveryHour scheduler;
    
    
    // method to schedule your actions
    private void scheduleEveryOneHour(){
    
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, 
                                                                     new Intent(WAKE_UP_AFTER_ONE_HOUR), 
                                                                     PendingIntent.FLAG_UPDATE_CURRENT);
    
            // wake up time every 1 hour
            Calendar wakeUpTime = Calendar.getInstance();
            wakeUpTime.add(Calendar.SECOND, 60 * 60);
    
            AlarmManager aMgr = (AlarmManager) getSystemService(ALARM_SERVICE);        
            aMgr.set(AlarmManager.RTC_WAKEUP,  
                     wakeUpTime.getTimeInMillis(),                 
                     pendingIntent);
    }
    
    //put this in the creation of service or if service is running long operations put this in onStartCommand
    
    scheduler = new FunctionEveryHour();
    registerReceiver(scheduler , new IntentFilter(WAKE_UP_AFTER_ONE_HOUR));
    
    // broadcastreceiver to handle your work
    class FunctionEveryHour extends BroadcastReceiver{
            @Override
            public void onReceive(Context context, Intent intent) {
                    // if phone is lock use PowerManager to acquire lock
    
                    // your code to handle operations every one hour...
    
                    // after that call again your method to schedule again
                    // if you have boolean if the user doesnt want to continue
                    // create a Preference or store it and retrieve it here like
                    boolean mContinue = getUserPreference(USER_CONTINUE_OR_NOT);//
    
                    if(mContinue){
                            scheduleEveryOneHour();
                    } 
            }
    }
    

    hope that helps :)

    0 讨论(0)
  • 2020-12-19 16:52

    Try this way,hope this will help you to solve your problem.

    new Timer().scheduleAtFixedRate(task, after, interval);
    
    0 讨论(0)
提交回复
热议问题