2016-11-28 47 views
1

我想獲得使用後臺服務的用戶的經度和緯度。我使用下面的代碼來獲取android中的經度和緯度。如何在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); 

這就是我所說的GPSTracker裏面的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; 

}

我無法獲得經緯度。 任何幫助或建議表示讚賞,謝謝。

+0

使用'FusedLocationApi' – Piyush

+0

好吧,我正在嘗試FusedLocationApi。但@Piyush我想獲得後臺服務的經緯度。 – anup

+0

檢查[this](http://javapapers.com/android/android-location-fused-provider/)和[this](http://stackoverflow.com/questions/34918675/android-location-service-didnt-工作在後臺) – Piyush

回答

3

使用下面的代碼...

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

使用此代碼來獲取在主線程中使用更新

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

} 
0

這是您需要從MainActivity類調用服務類。 該建議獲得位置更新,我用電熔位置提供: -

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(); 
    } 
}; 
相關問題