当用户第一次打开应用程序5分钟后,使用AlarmManager注册警报.创建服务(获取位置并更新到服务器)以在警报通知您的应用程序时运行.服务完成后,再次注册报警,5分钟后唤醒.通过这种方式,您可以实现您的任务.
REF
第一次编辑 – 添加代码示例
步骤1 – 创建警报管理器并注册警报
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(Main.this, YourWakefulReceiver.class);
bool flag = (PendingIntent.getBroadcast(Main.this, 0,
intent, PendingIntent.FLAG_NO_CREATE)==null);
/*Register alarm if not registered already*/
if(flag){
PendingIntent alarmIntent = PendingIntent.getBroadcast(Main.this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Create Calendar obj called calendar
Calendar calendar = Calendar.getInstance();
/* Setting alarm for every one hour from the current time.*/
int intervalTimeMillis = 1000 * 60 * 60; // 1 hour
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), intervalTimeMillis,
alarmIntent);
}
第2步 – 创建Receiver类
public class YourWakefulReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, SimpleWakefulService.class);
startWakefulService(context, service);
}
}
}
Setp 3 – 创建服务类
public class SimpleWakefulService extends IntentService {
private static String tagName = "YourService";
public SimpleWakefulService() {
super("YourService");
}
@Override
protected void onHandleIntent(Intent intent) {
// Start your location
LocationUtil.startLocationListener();
try {
// Wait for 10 seconds
Thread.sleep(1000*10);
} catch (InterruptedException e) {
}
//Stop location listener
LocationUtil.stopLocationListener();
// upload or save location
uploadGps();
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
}
第4步 – 注册服务和接收器
注意:此代码用于理解实现.它不会编译.