android我的位置定位服务器,在android中定期向服务器发送当前位置

当用户第一次打开应用程序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步 – 注册服务和接收器

注意:此代码用于理解实现.它不会编译.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值