我有一个Android应用程序,当他/她激活应用程序时,我将用户的数据存储在数据库中。我的应用程序要求用户手动停止应用程序,以便从数据库中删除其条目,以及在激活应用程序时继续运行的其他服务。
所以我想编写一个函数,该函数将在每小时后(当应用程序被激活时)执行,并且会向用户发出通知以提醒他/她正在运行的服务。如果用户忘记了停止服务然后他们可以停止服务或继续服务。
这样做的最有效方法是什么。如果用户认为它运行了一天左右,我不想用1小时的基础检查耗尽太多电池。请指教。谢谢:))
答案 0 :(得分:5)
我建议代码就是这样。
// 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();
}
}
}
希望有所帮助:)
答案 1 :(得分:2)
答案 2 :(得分:1)
请尝试这种方式,希望这有助于您解决问题。
new Timer().scheduleAtFixedRate(task, after, interval);