我有一个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();
}
}
}
希望能有所帮助:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句