【问题标题】:How do I get the last known location for the first time I execute a service?第一次执行服务时如何获取最后一个已知位置?
【发布时间】:2016-10-21 21:19:32
【问题描述】:

问题是我正在模拟器上尝试,它可以工作,但只有在我按下模拟器上的“将位置发送到设备”之后,但在此之前我没有机会获得位置...... .第一次使用该服务如何获取位置?我不知道真正的设备,模拟器是我目前测试的唯一方法.....我首先尝试发送 0,0 以查看是否会触发位置更新,但它不起作用还有……有什么想法吗?

@SuppressWarnings("MissingPermission")
public class GPSService extends Service {

    private LocationListener listener;
    private LocationManager locationManager;
    private String lastKnownLatitude;
    private String lastKnownLongitude;
    private Boolean isFirstTime=true;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();



        broadcastLocation("0","0");


        listener= new LocationListener() {
            @Override
             public void onLocationChanged(Location location) {

                //To transfer the data to the main activity I use broadcast receiver in the main activity, using an intent filter location_update
                 Intent intentSendLocationMainActivity = new Intent("location_update");
                lastKnownLatitude=""+location.getLatitude();
                lastKnownLongitude=""+location.getLongitude();
                Log.d("LOCATION-UPDATE",lastKnownLatitude+" long:"+lastKnownLongitude);
                broadcastLocation(lastKnownLatitude,lastKnownLongitude);
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
                Log.d("GPS-Stat-Changed",s);
            }

            @Override
            public void onProviderEnabled(String s) {
                Log.d("GPS-Provider-Enabled",s);
            }

            @Override
            public void onProviderDisabled(String s) {
                Intent activateGPSIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                activateGPSIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(activateGPSIntent);

            }
        };

        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        //noinspection MissingPermission, listen for updates every 3 seconds
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,listener);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ClearFromRecentService", "Service Started");
        Log.d("LAST_LAT_AND_LONG",lastKnownLatitude+" "+lastKnownLongitude);

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("ClearFromRecentService", "Service Destroyed, Removing update location listener");
        //unregistering the listener
        /*if(locationManager != null){
            locationManager.removeUpdates(listener);
        }*/

    }

    public void onTaskRemoved(Intent rootIntent) {
        Log.e("ClearFromRecentService", "END");
        //here you can call a background network request to post you location to server when app is killed
        Toast.makeText(getApplicationContext(), "I'm still getting user coordinates", Toast.LENGTH_LONG).show();
        //stopSelf(); //call this method to stop the service
    }

    public void broadcastLocation(String latitude,String longitude){
        Intent intentSendLocationMainActivity = new Intent("location_update");
        intentSendLocationMainActivity.putExtra("latitude",latitude);
        intentSendLocationMainActivity.putExtra("longitude",longitude);
        //I need to differentiate here if the app is killed or not to send the location to main activity or to a server
        sendBroadcast(intentSendLocationMainActivity);
    }
}

编辑:这是完整的服务工作。它第一次使用 getLastKnownLocation() 获取坐标,并使用侦听器 onLocationChanged() 获取连续时间

@SuppressWarnings("MissingPermission")
public class GPSService extends Service {

    private LocationListener listener;
    private LocationManager locationManager;
    private String lastKnownLatitude;
    private String lastKnownLongitude;
    private Boolean isFirstTime=true;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        listener= new LocationListener() {
            @Override
             public void onLocationChanged(Location location) {

                //To transfer the data to the main activity I use broadcast receiver in the main activity, using an intent filter location_update
                 Intent intentSendLocationMainActivity = new Intent("location_update");
                lastKnownLatitude=""+location.getLatitude();
                lastKnownLongitude=""+location.getLongitude();
                Log.d("LOCATION-UPDATE",lastKnownLatitude+" long:"+lastKnownLongitude);
                broadcastLocation(lastKnownLatitude,lastKnownLongitude);
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
                Log.d("GPS-Stat-Changed",s);
            }

            @Override
            public void onProviderEnabled(String s) {
                Log.d("GPS-Provider-Enabled",s);
            }

            @Override
            public void onProviderDisabled(String s) {
                Intent activateGPSIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                activateGPSIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(activateGPSIntent);

            }
        };

        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        //noinspection MissingPermission, listen for updates every 3 seconds
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,listener);


        Map<String, String> coordinates=getLastKnownLocation(locationManager);
        broadcastLocation(coordinates.get("latitude"),coordinates.get("longitude"));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ClearFromRecentService", "Service Started");
        Log.d("LAST_LAT_AND_LONG",lastKnownLatitude+" "+lastKnownLongitude);

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("ClearFromRecentService", "Service Destroyed, Removing update location listener");
        //unregistering the listener
        /*if(locationManager != null){
            locationManager.removeUpdates(listener);
        }*/

    }

    public void onTaskRemoved(Intent rootIntent) {
        Log.e("ClearFromRecentService", "END");
        //here you can call a background network request to post you location to server when app is killed
        Toast.makeText(getApplicationContext(), "I'm still getting user coordinates", Toast.LENGTH_LONG).show();
        //stopSelf(); //call this method to stop the service
    }

    private void broadcastLocation(String latitude,String longitude){
        Intent intentSendLocationMainActivity = new Intent("location_update");
        intentSendLocationMainActivity.putExtra("latitude",latitude);
        intentSendLocationMainActivity.putExtra("longitude",longitude);
        //I need to differentiate here if the app is killed or not to send the location to main activity or to a server
        sendBroadcast(intentSendLocationMainActivity);
    }

    private Map<String, String> getLastKnownLocation(LocationManager lm){

        Location lastKnownLocation=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        String ll=""+lastKnownLocation.getLatitude();
        Map<String, String> coordinates = new HashMap<String, String>();


        // Check everytime this value, it may be null
        if(lastKnownLocation != null){
            coordinates.put("latitude",""+lastKnownLocation.getLatitude());
            coordinates.put("longitude",""+lastKnownLocation.getLongitude());

        }else{
            coordinates.put("latitude","0");
            coordinates.put("longitude","0");
        }

        return coordinates;
    }
}

【问题讨论】:

  • 在onCreate你可以使用getLastKnownLocation(LocationManager.GPS_PROVIDER);
  • 我用调试器试过这个,它在我调用 getLastKnownLocation 的线路上崩溃.....@Override public void onCreate() { super.onCreate(); Location lastKnownLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 你能提供一个关于你建议的代码 sn-p 吗?谢谢!

标签: java android android-service


【解决方案1】:
@Override
public void onCreate() {
    super.onCreate();

    locationManager = (LocationManager) getApplicationContext()
        .getSystemService(Context.LOCATION_SERVICE);

    Location lastKnownLocation = locationManager
        .getLastKnownLocation(Locat‌​ionManager.GPS_PROVI‌​DER); 

    // Check everytime this value, it may be null
    if(lastKnownLocation != null){
        double latitude = lastKnownLocation.getLatitude();
        double longitude = lastKnownLocation.getLongitude();
        // Use values as you wish
    }

    broadcastLocation("0","0");


    ....
}

【讨论】:

  • 事实上,在locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,listener); 之后移动这条线Location lastKnownLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 就完美了......我把它放在onCreate 的开头。看起来 getLastKnownLocation 需要在 requestLocationUpdates 方法工作之后运行。非常感谢楼主!
  • 我用最终代码更新了我的帖子以供将来参考。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 2014-10-18
相关资源
最近更新 更多