如何在android中使用后台服务获取纬度和经度? [英] How to get latitude and longitude using a background service in android?
本文介绍了如何在android中使用后台服务获取纬度和经度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获得用户使用后台服务的经度和纬度。我使用下面的代码来获取android中的经度和纬度。
private static final String TAG =BOOMBOOMTESTGPS;
私人LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 10;
private static final float LOCATION_DISTANCE = 0;
Handler mHandler = new Handler();
public SharedPreferences pref;
GoogleApiClient mGoogleApiClient = null;
位置mLastLocation;
双纬度,经度;
@Override
public int onStartCommand(Intent intent,int flags,int startId){
Log.e(TAG,onStartCommand);
super.onStartCommand(intent,flags,startId);
返回START_STICKY;
}
@Override
public void onCreate(){
super.onCreate();
Log.e(TAG,onCreate);
initializeLocationManager();
尝试{
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,LOCATION_INTERVAL,LOCATION_DISTANCE,
mLocationListeners [1]);
} catch(java.lang.SecurityException ex){
Log.i(TAG,无法请求位置更新,忽略,前);
} catch(IllegalArgumentException ex){
Log.d(TAG,网络提供者不存在,+ ex.getMessage());
}
尝试{
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,LOCATION_INTERVAL,LOCATION_DISTANCE,
mLocationListeners [0]);
} catch(java.lang.SecurityException ex){
Log.i(TAG,无法请求位置更新,忽略,前);
} catch(IllegalArgumentException ex){
Log.d(TAG,gps provider does not exist+ ex.getMessage());
$ b @Override
public void onDestroy(){
Log.e(TAG,onDestroy);
super.onDestroy();
if(mLocationManager!= null){
for(int i = 0; i< mLocationListeners.length; i ++){
try {
if(ActivityCompat.checkSelfPermission(this ,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED&&&& ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
// TODO :考虑调用
// ActivityCompat#requestPermissions
//在这里请求丢失的权限,然后覆盖
// public void onRequestPermissionsResult(int requestCode,String [] permissions,
// int [] grantResults)
//处理用户授予权限的情况。有关更多详细信息,请参阅文档
//获取ActivityCompat#requestPermissions。
return;
}
mLocationManager.removeUpdates(mLocationListeners [i]);
} catch(Exception ex){
Log.i(TAG,无法移除位置列表,忽略,ex);
$ b private void initializeLocationManager(){
Log.e(TAG,initializeLocationManager);
if(mLocationManager == null){
mLocationManager =(LocationManager)getApplicationContext()。getSystemService(Context.LOCATION_SERVICE);
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider){
Log.e(TAG,LocationListener+ provider);
mLastLocation =新位置(供应商);
@Override
public void onLocationChanged(Location location){
Log.e(TAG,onLocationChanged:+ location);
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d(LATLANG:,latitude ++ longitude);
mLastLocation.set(location);
}
@Override
public void onProviderDisabled(String provider){
Log.e(TAG,onProviderDisabled:+ provider);
}
@Override
public void onProviderEnabled(String provider){
Log.e(TAG,onProviderEnabled:+ provider);
$ b @Override
public void onStatusChanged(String provider,int status,Bundle extras){
Log.e(TAG,onStatusChanged:+ provider) ;
LocationListener [] mLocationListeners = new LocationListener [] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER )
};
@Nullable
@Override
public IBinder onBind(Intent intent){
return null;
$ / code>
我从我的活动中使用以下代码:
Intent start_intent = new Intent(DaLoginActivity.this,MyService.class);
startService(start_intent);
这是我在MyService中调用GPSTracker的地方: - $ /
@Override
public int onStartCommand(Intent intent,int flags,int startId){
Log.e(TAG,onStartCommand);
super.onStartCommand(intent,flags,startId);
GPSTracker gps =新GPSTracker(this);
if(gps.canGetLocation()){
gps.getLatitude(); //返回纬度
gps.getLongitude();
$ b Toast.makeText(gps,Latitude:+ gps.getLatitude()++ gps.getLongitude(),Toast.LENGTH_SHORT).show();
返回START_STICKY;
}
我无法取得经纬度。
感谢您的任何帮助或建议。
public class RTGPSLocationService extends Service {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 5000; //以毫秒为单位
保护LocationManager locationManager;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
private final String TAG =RTGPSLocationService;
@Override
public IBinder onBind(Intent arg0){
return null;
}
@Override
public void onCreate(){
super.onCreate();
RTLog.d(标记,GPS服务已创建...);
locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
RTLog.d(RTGPSLocationService,+ isGPSEnabled ++ isNetworkEnabled);
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!=
PackageManager.PERMISSION_GRANTED&&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
RTLog.d(TAG,位置权限被拒绝);
} else {
if(isGPSEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,new MyLocationListener());
位置位置= locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} else if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,new MyLocationListener());
位置位置= locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
callLocationDetailAPI(location);
@Override
public void onDestroy(){
super.onDestroy();
RTLog.d(TAG,GPS Service destroyed destroyed ...);
$ b private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location){
String message = String.format(New Location \\\
Longitude: %1 $ s \\\
Latitude:%2 $ s,
location.getLongitude(),location.getLatitude());
RTLog.d(TAG,location.getLatitude()++ location.getLongitude());
RTLog.d(TAG,message);
callLocationDetailAPI(location);
$ b $ public void onStatusChanged(String s,int i,Bundle b){
}
public void onProviderDisabled(String s){
$ b $ public void onProviderEnabled(String s){
}
}
}
I want to get the latitude and longitude of the user using a background service.I am using the following code to get the latitude and longitude in android.
public class MyService extends Service {
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 10;
private static final float LOCATION_DISTANCE = 0;
Handler mHandler = new Handler();
public SharedPreferences pref;
GoogleApiClient mGoogleApiClient = null;
Location mLastLocation;
Double latitude, longitude;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("LATLANG : ", latitude + " " + longitude);
mLastLocation.set(location);
}
@Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
And I am calling the service from my activity using the following code:
Intent start_intent = new Intent(DaLoginActivity.this, MyService.class);
startService(start_intent);
This is where I call GPSTracker inside MyService:-
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
GPSTracker gps = new GPSTracker(this);
if(gps.canGetLocation()){
gps.getLatitude(); // returns latitude
gps.getLongitude();
}
Toast.makeText(gps, "Latitude : "+gps.getLatitude()+" "+gps.getLongitude(), Toast.LENGTH_SHORT).show();
return START_STICKY;
}
I am unable to get the latitude and longitude. Any help or suggestion is appreciated.Thank you.
解决方案
Use the following code...
public class RTGPSLocationService extends Service {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 5000; // in Milliseconds
protected LocationManager locationManager;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
private final String TAG = "RTGPSLocationService";
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
RTLog.d(TAG, "GPS Service created ...");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
RTLog.d("RTGPSLocationService", " " + isGPSEnabled + " " + isNetworkEnabled);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
RTLog.d(TAG, "Location Permission is declined");
} else {
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} else if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
callLocationDetailAPI(location);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
RTLog.d(TAG, "GPS Service destroyed ...");
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format("New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
RTLog.d(TAG, location.getLatitude() + " " + location.getLongitude());
RTLog.d(TAG, message);
callLocationDetailAPI(location);
}
public void onStatusChanged(String s, int i, Bundle b) {
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
}
}
这篇关于如何在android中使用后台服务获取纬度和经度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文