Gradles
compile 'com.google.android.gms:play-services-maps:10.0.1' /*Google Maps*/
compile 'com.google.android.gms:play-services-location:10.0.1'
apply plugin: 'com.google.gms.google-services'Dependenciesclasspath 'com.google.gms:google-services:3.0.0'
Location Service
import android.Manifest; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 2000; /** * 60000 1 min */ public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2; /** * 1sec */ private static final int DISPLACEMENT_DISTANCE = 5; /* 1000=1 km*/ private static final String TAG = "LocationService"; private GoogleApiClient mGoogleApiClient; private LocationRequest mLocationRequest; SharedPreferences pref; @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "Service onStartCommand"); pref = getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE); buildGoogleApiClient(); return START_STICKY; } protected synchronized void buildGoogleApiClient() { LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); boolean isGPSEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER); boolean isNetworkEnabled = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); // if (!isGPSEnabled && !isNetworkEnabled) {// buildAlertMessageNoGps();// } else { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); createLocationRequest(); // } } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setSmallestDisplacement(DISPLACEMENT_DISTANCE); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } protected void startLocationUpdates() { 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; } LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this); } protected void stopLocationUpdates() { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } // private void buildAlertMessageNoGps() {// final AlertDialog.Builder builder = new AlertDialog.Builder(this);// builder.setMessage(getString(R.string.msg_alert_gps))// .setCancelable(false)// .setPositiveButton(getString(R.string.str_yes), new DialogInterface.OnClickListener() {// public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {// dialog.cancel();// startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));// }// })// .setNegativeButton(getString(R.string.str_no), new DialogInterface.OnClickListener() {// public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {// dialog.cancel();// }// });// final AlertDialog alert = builder.create();// alert.show();// } @Override public void onConnected(Bundle bundle) { Log.e(TAG, "Service Connect"); 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; } if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (location == null) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } else { // handleNewLocation(location); } /**update location frequently**/ startLocationUpdates(); } } @Override public void onConnectionSuspended(int i) { mGoogleApiClient.connect(); } @Override public void onConnectionFailed(ConnectionResult connectionResult) { Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode()); if (connectionResult.hasResolution()) { Log.e(TAG, "onConnectionFailed: " + connectionResult.getErrorMessage()); // try {// // Start an Activity that tries to resolve the error// connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);// } catch (IntentSender.SendIntentException e) {// e.printStackTrace();// } } else { Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode()); } } @Override public void onLocationChanged(Location location) { Log.e(TAG, "onLocationChanged: location=" + location.getLongitude()); Log.e(TAG, "onLocationChanged: location=" + location.getLatitude()); handleNewLocation(location); /**send broadcast to update current location when app is open*/ Intent broadcastIntent = new Intent(); broadcastIntent.setAction(WebServiceParams.UPDATE_LOCATION); broadcastIntent.putExtra(Constants.EXTRA_CURRENT_LOCATION, location); sendBroadcast(broadcastIntent); } private void handleNewLocation(Location location) { SharedPreferences.Editor editor = pref.edit(); editor.putLong(Constants.PREF_CURRENT_LATITUDE, Double.doubleToLongBits(location.getLatitude())); editor.putLong(cConstants.PREF_CURRENT_LONGITUDE, Double.doubleToLongBits(location.getLongitude())); editor.apply(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); Log.e(TAG, "onDestroy: service destroy"); } /* @Override public void onDestroy() { super.onDestroy(); Log.e(TAG, "onDestroy: service destroy"); if (mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); mGoogleApiClient.disconnect(); } }*/ }
Comments
Post a Comment