1小时后的And​​r​​oid执行一个功能功能、小时后、And、oid

2023-09-06 08:06:19 作者:勒非 .

我有我在哪里存储数据库用户的数据时,他/她会激活应用程序的Andr​​oid应用。我的应用程序需要用户以手动停止应用程序从数据库中删除,并沿与保持,当应用程序被激活运行其他服务的条目。

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.

这是这样做的最佳效率的方式。我不想用thihs1小时基础检查地漏太多的电池,如果用户认为它为一天左右运行。请指教。感谢:)

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

推荐答案

我建议code还会是这样。

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();
                } 
        }
}

希望帮助:)

 
精彩推荐
图片推荐