我正在做一个小的android应用程序,我想有一些代码,每天早上6点运行一次当应用程序没有运行时,更新一些参数,并向用户发送通知,告诉他们进入应用程序。有人能告诉我做这件事的最好方法吗?
发布于 2015-06-26 03:30:07
您可以使用警报管理器、待定意图和广播接收器来执行此操作。此代码将每两小时唤醒设备一次:
AlarmManager alarmManager = (AlarmManager)this.getSystemService(ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
//set the alarms to start in the time period
cal.add(Calendar.MILLISECOND,60000);
Intent i = new Intent(this, AlarmBroadcastReceiver.class);
PendingIntent getSqlUpdatesTimer = PendingIntent.getBroadcast(this, 0, i, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 7200000, getSqlUpdatesTimer);和你的广播接收器:
public class AlarmBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
if (intent != null) {
PowerManager pm = (PowerManager)context.getSystemService(context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wl.acquire();
//Some code to do your task
wl.release();
}
}
}您还需要在Manifest中设置wakelock权限。
https://stackoverflow.com/questions/31059051
复制相似问题