Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android execute a function after 1 hour

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 to remove its entry from the database and along with that other services which keep running when the app is activated.

So I want to write a function which will be executed after every hour (when the app is activated) and will give a notification to user just to remind him/her about the service which is running .If the user had forgot to stop the service then they can stop it or continue with service.

What is the best efficient way of doing this. I dont want to drain too much of battery with thihs 1 hour basis check if the user considers it to run for a day or so. Please advice. Thanks :)

like image 791
ik024 Avatar asked Jan 10 '23 00:01

ik024


1 Answers

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 :)

like image 169
Spurdow Avatar answered Jan 17 '23 18:01

Spurdow