Android 在 1 小时后执行一个函数

标签 android performance timer android-asynctask

我有一个 android 应用程序,当他/她激活该应用程序时,我将用户的数据存储在数据库中。我的应用程序要求用户手动停止应用程序,以便从数据库中删除其条目以及在激活应用程序时继续运行的其他服务。

所以我想编写一个函数,该函数将在每小时后(当应用程序被激活时)执行,并向用户发出通知,只是提醒他/她正在运行的服务。如果用户忘记了停止服务,然后他们可以停止或继续服务。

执行此操作的最有效方法是什么。如果用户认为它可以运行一天左右,我不想以 1 小时为基础检查耗尽太多电池。请指教。谢谢:)

最佳答案

我建议代码是这样的。

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

希望对您有所帮助:)

关于Android 在 1 小时后执行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25375968/

相关文章:

android - 具有非数据库内容提供者的 Matrixcursor

更新gradle后Android单元测试无法解析被测类

java - Android 上的 java.io 方法是否会抛出 InterruptedIOException?

Java,断言文件等于

javascript - 非javascript定时器

c - 使用 Time 获取当前日期的天数

php - Android PHP 查询不起作用

php - php 在没有警告的情况下运行得更快吗?

node.js - Nodejs + phantomjs 与纯 phantomjs - 页面加载时间

java - 安排给定时间的工作