android - 如何使用 Android 中的后台服务每 5 分钟获取一次设备位置?

标签 android service geolocation location android-intentservice

我想每 5 分钟获取一次用户位置并显示为 Toast。哪种方法最好? 服务还是IntentService?我想通过单击按钮启动和停止服务。怎么做?

最佳答案

使用报警服务触发位置服务,将位置保存在数据库表中

public static void setAlarmTimely(Context context) {
    AlarmManager alarmMgr;
    PendingIntent alarmIntent;

    alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(IntentConstants.ALARM_INTENT, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK);
    alarmIntent = PendingIntent
            .getBroadcast(context, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK, intent, 0);
    alarmMgr.cancel(alarmIntent);

    Calendar calendar = Calendar.getInstance();
    LOGD(TAG, time + " ");
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + locationCaptureTime * 60 * 1000,
            5 * 60 * 1000, alarmIntent);
}

点击按钮取消闹钟

AlarmManager alarmMgr;
    PendingIntent alarmIntent;
    LOGD(TAG, "cancelling location update");
    alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(IntentConstants.ALARM_INTENT, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK);
    alarmIntent = PendingIntent
            .getBroadcast(context, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK, intent, 0);
    alarmMgr.cancel(alarmIntent);

关于android - 如何使用 Android 中的后台服务每 5 分钟获取一次设备位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38139125/

相关文章:

android - 自动缩放 TextView 文本以适应边界

Android 按钮 onclick 提交到电子邮件

google-app-engine - Appengine LogService 有一个未记录的配额 - 每天最多 1000000 次读取,知道解决方法吗?

javascript - 我可以允许出于开发目的对不安全的来源进行地理定位吗?

ios - 如何提高区域边界穿越精度(模拟)(地理围栏)

java - 使用 TextInputEditText 在 RecyclerView 中遇到问题

android - 谷歌登录在 Release模式apk android下不起作用

跨多项 Activity 的 Android 全面防故障音乐服务

android - 使用 this.setVolumeControlStream(AudioManager.STREAM_MUSIC);当 Activity 失焦时控制 android 手机摇杆(有服务)?

android - 如何在 Android 中获取位置管理器的最后已知位置?