Android在手机启动后获取GPS位置,我试图在服务中获取它,但位置返回为空
这是代码 我如何确定,该位置返回的是alwasys而不是nullAndroid在手机启动后获取GPS位置,我试图在服务中获取它,但位置返回为空,android,service,gps,location,boot,Android,Service,Gps,Location,Boot,这是代码 我如何确定,该位置返回的是alwasys而不是null package com.test.location; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location
package com.test.location;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
public class NotifyOnBoot extends Service {
Location location;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
updateNotification();
Thread th = new Thread(null, task, "myService");
th.start();
}
private Runnable task = new Runnable() {
public void run() {
if(location == null)
{
Log.d("location","No location");
}
else
Log.d("location",location.toString());
NotifyOnBoot.this.stopSelf();
}
};
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand (Intent intent, int flags, int startId){
return START_STICKY;
}
protected void updateNotification()
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
private class MyLocationlistener implements LocationListener{
public void onLocationChanged(Location location){}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status, Bundle extras){}
}
}
我建议创建一个回调接口并使用onLocationChanged,它在位置第一次启动时通知回调
LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
我希望这对您有所帮助。请您具体说明:创建一个处理程序并将其用作回拨。因此,当处理程序被调用时,只需使用lat-long坐标。嗨,rohit,当我在emulator中更改位置时,我能够获取位置,但我想要的是在手机启动时始终获取当前位置或最后已知的位置