我目前正在开展一个项目,包括每5秒获取当前位置。我为此创建了一项服务。但目前的位置没有得到。我尝试this link.但我没有获得当前的位置。
public class Locfetching extends Service{
LocationManager locationManager;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("2", "2");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListener myLocationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, myLocationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.e("SERVICE123", "LATITUDE:- "+ location.getLatitude() + " Longitude:- " + location.getLongitude());
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.e("1", "1");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("3", "3");
if (locationManager != null) {
locationManager = null;
}
}
public class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("SERVICE", "LATITUDE:- "+ location.getLatitude() + " Longitude:- " + location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
} }
如何在后台获取当前位置?
答案 0 :(得分:0)
您是否检查过该手机的位置服务?它启用了吗?如果它似乎已启用,请将其关闭然后再点击同意(在Android 4+设备的情况下)。然后检查,它应该工作。还要检查是否在清单中添加了相同的权限。
答案 1 :(得分:0)
你没有做足够的研究What is the simplest and most robust way to get the user's current location on Android?是最好的,我可以为你提供
答案 2 :(得分:0)
尝试检查位置提供程序是否已启用。
另外,请检查您是否获得了网络提供商的位置
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, myLocationListener);
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 1, myLocationListener);
}