Android 位置更新作为后台服务

标签 android location background-service

我是 Android 新手,正在开发一个应用程序,以实现即使应用程序退出也能获取位置更新的功能。即,无论我的应用程序的状态如何,它都应该不断更新我在服务器中的当前位置终止。

你们能建议我应该采取什么方法吗? 非常感谢您的帮助...

最佳答案

下面是使用处理程序每​​ X 分钟或每 X 米获取用户位置的代码。

Location gpslocation = null;

    private static final int GPS_TIME_INTERVAL = 60000; // get gps location every 1 min
    private static final int GPS_DISTANCE= 1000; // set the distance value in meter

    /*
       for frequently getting current position then above object value set to 0 for both you will get continues location but it drown the battery
    */

    private void obtainLocation(){
    if(locMan==null)
        locMan = (LocationManager) getSystemService(LOCATION_SERVICE);

        if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if(isLocationListener){
                 locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
                            GPS_TIME_INTERVAL, GPS_DISTANCE, GPSListener);
                    }
                }
            }
    }

处理程序

    private static final int HANDLER_DELAY = 1000*60*5;

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
            public void run() {
                myLocation = obtainLocation();
                handler.postDelayed(this, HANDLER_DELAY);
            }
        }, START_HANDLER_DELAY);

GPS位置监听器

private LocationListener GPSListener = new LocationListener(){
    public void onLocationChanged(Location location) {
        // update your location

    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
};

关于Android 位置更新作为后台服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36545298/

相关文章:

java - 使用 OpenCV 洪水填充

ruby-on-rails - Rails - 在哪里放置数据文件?

android - 使用 Realm 过滤和排序附近的位置

java - java中for循环内部的后台服务调用?

安卓蓝牙后台监听

android - 在android中无限运行服务

android - 显示 png 时隐藏 1px 边距

android - 登录(安卓): SizeBasedTriggeringPolicy not working

android - 排毒 - 无法初始化类 DefaultKotlinSourceSetKt

android - Google Map Api 中的 PlaceAutoComplete