【问题标题】:How to get latitude and longitude using a background service in android?如何使用android中的后台服务获取纬度和经度?
【发布时间】:2016-11-28 11:32:26
【问题描述】:

我想通过后台服务获取用户的经纬度。我在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;
    }
}

我正在使用以下代码从我的活动中调用服务:

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 = 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;

}

我无法获得纬度和经度。 感谢您提供任何帮助或建议。谢谢。

【问题讨论】:

  • 使用FusedLocationApi
  • 好的,我正在尝试 FusedLocationApi。但是@Piyush我想在后台服务中获取纬度和经度。
  • 检查thisthis

标签: java android google-maps service latitude-longitude


【解决方案1】:

使用下面的代码...

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) {
        }
    }
}

【讨论】:

    【解决方案2】:

    这是您需要从 MainActivity 类调用的服务类。 我使用了推荐获取位置更新的 Fused Location Provider:-

    public class LocationService extends Service implements LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {
    
    Intent intent;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    String lat, lon;
    public static String str_receiver = "servicetutorial.service.receiver";
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onCreate() {
        Log.d("Service started Getting", "started!!!!!!!!!!");
    
        super.onCreate();
        buildGoogleApiClient();
        intent = new Intent(str_receiver);
    
    }
    
    synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }
    
    
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.d("Connected:Getting ", "LOcation!!!!!!!!!!");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(30000);
        mLocationRequest.setFastestInterval(30000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
       /* if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
    
        }*/
    
        //use if you want location update
    
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
        Log.d("LocationUpdatesRequest", "Granted");
        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;
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            lat = String.valueOf(mLastLocation.getLatitude());
            lon = String.valueOf(mLastLocation.getLongitude());
    
            intent.putExtra("latutide",mLastLocation.getLatitude()+"");
            intent.putExtra("longitude",mLastLocation.getLongitude()+"");
            sendBroadcast(intent);
    
            Log.d("Latitue!!!!",lat);
            Log.d("Longitude!!!!",lon);
    
        }
        else{
            Log.d("Failed","Connection");
            //Toast.makeText(this,"Failed",Toast.LENGTH_LONG).show();
        }
    }
    
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
    
    /*@Override
    public void onConnected(@Nullable Bundle bundle) {
    
    }*/
    
    @Override
    public void onConnectionSuspended(int i) {
    
    }
    
    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        lat = String.valueOf(location.getLatitude());
        lon = String.valueOf(location.getLongitude());
        String msg = "Updated Location: " +
                Double.toString(location.getLatitude()) + "," +
                Double.toString(location.getLongitude());
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        Log.d("changed","after 30");
    
    }
    
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    
    }
    

    }

    现在从主要活动调用服务:-

    startService(new Intent(MainActivity.this, LocationService.class));
                Toast.makeText(MainActivity.this ,"started",Toast.LENGTH_SHORT).show();
    

    并在MainActivity中添加广播接收器:-

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(MainActivity.this ,"Broadcast receinved", Toast.LENGTH_SHORT).show();
    
            latitude = Double.valueOf(intent.getStringExtra("latutide"));
            longitude = Double.valueOf(intent.getStringExtra("longitude"));
    
            List<Address> addresses = null;
            try { addresses = geocoder.getFromLocation(latitude, longitude, 1);
                String cityName = addresses.get(0).getAddressLine(0);
                String stateName = addresses.get(0).getAddressLine(1);
                String countryName = addresses.get(0).getAddressLine(2);
                area.setText(addresses.get(0).getAdminArea());
                tv_locality.setText(stateName);
                tv_address.setText(countryName); }
            catch (IOException e1)
            { e1.printStackTrace();
            }
            tv_latitude.setText(latitude+"");
            tv_longitude.setText(longitude+"");
            tv_address.getText();
        }
    };
    

    【讨论】:

      【解决方案3】:

      使用此代码在主线程中获取更新

      locateme = new GPSTracker(Home.this);
      
      if(locateme.canGetLocation()) {
           final double latitude = locateme.getLatitude();
           final double longitude = locateme.getLongitude();
           final float spd = locateme.getSpeed();
      }
      

      通过这个后台跟踪服务

      public class GPSTracker extends Service implements LocationListener {
      
          private final Context context;
      
          boolean isGPSEnabled = false;
          boolean isNetworkEnabled = false;
          boolean canGetLocation = false;
      
          Location location;
      
          double latitude;
          double longitude;
          float spd;
      
          private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
          private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
      
          protected LocationManager locationManager;
      
          public GPSTracker(Context context) {
              this.context = context;
              getLocation();
          }
      
          public Location getLocation() {
              try {
                  locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
      
                  isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
      
                  isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
      
                  if (!isGPSEnabled && !isNetworkEnabled) {
      
                  } else {
                      this.canGetLocation = true;
      
      
                      if (isGPSEnabled) {
                          if (location == null) {
                              locationManager.requestLocationUpdates(
                                      LocationManager.GPS_PROVIDER,
                                      MIN_TIME_BW_UPDATES,
                                      MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
      
                              if (locationManager != null) {
                                  location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
      
                                  if (location != null) {
                                      latitude = location.getLatitude();
                                      longitude = location.getLongitude();
                                      spd = location.getSpeed();
                                  }
                              }
                          }
                      }
                      if (isNetworkEnabled) {
      
      
                          if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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 null;
                          }
                          locationManager.requestLocationUpdates(
                                  LocationManager.NETWORK_PROVIDER,
                                  MIN_TIME_BW_UPDATES,
                                  MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
      
                              if (locationManager != null) {
                                  location = locationManager
                                          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
      
                                  if (location != null) {
      
                                      latitude = location.getLatitude();
                                      longitude = location.getLongitude();
                                      spd = location.getSpeed();
                                  }
                              }
      
      
      
                      }
                  }
      
              } catch (Exception e) {
                  e.printStackTrace();
              }
      
              return location;
          }
      
      
          public void stopUsingGPS() {
              if (locationManager != null) {
      
                  locationManager.removeUpdates(GPSTracker.this);
              }
          }
      
          public double getLatitude() {
              if(location != null) {
                  latitude = location.getLatitude();
              }
              return latitude;
          }
      
          public double getLongitude() {
              if(location != null) {
                  longitude = location.getLongitude();
              }
      
              return longitude;
          }
      
          public float getSpeed() {
              if(location != null) {
                  spd = location.getSpeed();
              }
      
              return spd;
          }
      
          public boolean canGetLocation() {
              return this.canGetLocation;
          }
      
          public void showSettingsAlert() {
              AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
      
              alertDialog.setTitle("GPS is settings");
      
              alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
      
              alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
      
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                      context.startActivity(intent);
                  }
              });
      
              alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      dialog.cancel();
                  }
              });
      
              alertDialog.show();
          }
      
          @Override
          public void onLocationChanged(Location arg0) {
              // TODO Auto-generated method stub
      
          }
      
          @Override
          public void onProviderDisabled(String arg0) {
              // TODO Auto-generated method stub
      
          }
      
          @Override
          public void onProviderEnabled(String arg0) {
              // TODO Auto-generated method stub
      
          }
      
          @Override
          public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
              // TODO Auto-generated method stub
      
          }
      
          @Override
          public IBinder onBind(Intent intent) {
              // TODO Auto-generated method stub
              return null;
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2017-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-02
        相关资源
        最近更新 更多