我試圖做一個定位服務,但不知怎的,我不能讓它工作。 Lat和Lng始終爲NULL。從服務中獲取位置數據?
我對locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
有一些例外,所以我把它放在run()的方法裏,現在異常消失了。可能是什麼問題呢?
那麼定位服務的解決方案是什麼?
代碼:
public class LocationService extends Service {
private Timer timer = new Timer();
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private String latitude;
private String longitude;
private String providerToSend;
Messenger messenger;
Timer t = new Timer();
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onCreate() {
super.onCreate();
locListener = new MyLocationListener();
locationProviderInit();
startService();
}
@Override
public void onDestroy() {
super.onDestroy();
shutdownService();
}
private void startService() {
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String token = new SharedPreffer(this).loadPreferences("token");
Log.d("Debug - token: ", "Van Token: " + token);
t.schedule(new TimerTask() {
@Override
public void run() {
locationProviderInit();
if (latitude != null && longitude != null) {
Log.d("Debug - lat: ", latitude);
Log.d("Debug - lng: ", longitude);
} else {
Log.d("Debug - lat and lng are: ", "NULL");
}
}
}, 0, 5000);
}
private void locationProviderInit() {
new Runnable() {
@Override
public void run() {
try {
boolean gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
providerToSend = LocationManager.GPS_PROVIDER;
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
providerToSend = LocationManager.NETWORK_PROVIDER;
}
} catch (Exception e) {
Log.d("Debug", e.toString());
}
}
};
}
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
longitude = Double.toString(location.getLongitude());
latitude = Double.toString(location.getLatitude());
}
}
public void onProviderDisabled(String arg) {
}
public void onProviderEnabled(String arg) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private void shutdownService() {
if (timer != null)
timer.cancel();
Log.i(getClass().getSimpleName(), "Timer stopped!!!");
}
}
是什麼異常? – iTech