Using Google API for GPS

Using Google API for GPS


This post will show you how implement a Google Service


Step 1

Enable the service on AndroidManifest.xml

        <service android:name="mx.com.yourAppName.Globals.GpsService">
        </service>


Step 2


Add this class.

This class can mantain service on and show an alert window if the GPS service in off and send to activate service.

package mx.com.yourAppName.Globals;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

/* Google api */
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.LocationServices;
import com.google.android.gms.location.LocationRequest;



public class GpsService extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,LocationListener {

    private Context mContext;
    public double latitud = 0;
    public double longitud = 0;
    String _TAG = "PGS_Service";

    /* local vars GoogleApiClient */
    GoogleApiClient mGoogleApiClient;
    public Location mLocation;


    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

    protected LocationManager locationManager;

    public GpsService(){}

    public GpsService(Context context){
        Log.w(_TAG, "Constructor GpsService");
        this.mContext = context;

        mGoogleApiClient = new GoogleApiClient.Builder(this.mContext)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mGoogleApiClient.connect();

    }

    public double getLatitud() {
        return latitud;
    }

    public void setLatitud(double latitud) {
        this.latitud = latitud;
    }

    public double getLongitud() {
        return longitud;
    }

    public void setLongitud(double longitud) {
        this.longitud = longitud;
    }

    /* from interfaces OnConnectionFailedListener */

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult){
        Log.e(_TAG, "Error on connect GPS");
    }

    public void startLocationUpdates(){

        if(!isGpsEnabled()){
            Log.e(_TAG, "Error. GPS is disabled");
            showSettingsAlert();
            return;
        }

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {

                if(ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                    Log.e(_TAG, "Error with permissions");
                    showSettingsAlert(); //BCA20032019 Marca error si no no tiene permisos
                }else{
                    Log.w(_TAG, "Permission its ok");
                    //mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); // Obtiene las ultimas coordenadas
                    if(mLocation!=null){
                        Log.w(_TAG, "mLocation is not null");
                        Log.w(_TAG, "Latitude : "+mLocation.getLatitude()+" , Longitude : "+mLocation.getLongitude());
                        //Toast.makeText(this.mContext ,"Latitude : "+mLocation.getLatitude()+" , Longitude : "+mLocation.getLongitude() ,Toast.LENGTH_LONG).show();
                        latitud = mLocation.getLatitude();
                        longitud = mLocation.getLongitude();

                        setLatitud(latitud);
                        setLongitud(longitud);
                        Log.w(_TAG, "Setting Latitud:" + getLatitud() + " Longitud:" + getLongitud() );

                    }else{
                        Log.e(_TAG, "mLocation is NULL!");
                        Toast.makeText(mContext ,"Porfavor debe habilitar el GPS" ,Toast.LENGTH_LONG).show();
                        mGoogleApiClient.reconnect();
                        startLocationUpdates();
                    }
                }


            }
        }, 5000);

    }

    @Override
    public void onConnected(@Nullable Bundle bundle){
        Log.w(_TAG, "GPS connected");
        LocationRequest mLocationRequest;
        long UPDATE_INTERVAL = 5000; /* mili seconds */
        long FASTEST_INTERVAL = 1000; /* milisecosnds */
        mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if( mContext.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && mContext.checkSelfPermission( Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED  ){

                return;
            }else{
                Log.w(_TAG, "Todos los permisos correctos");
            }
        }else{
            Log.w(_TAG, "Es menor a 23");
        }

        if(mGoogleApiClient.isConnected()){
            Log.w(_TAG, "mGoogleApiClient is connected");
            try {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, GpsService.this);
            }catch (Exception e){
                Log.e(_TAG,"Se requiere que se habilten los permisos");
            }
        }else{
            Log.e(_TAG, "ERROR mGoogleApiClient is not connected");

        }
        this.startLocationUpdates();
    }

    // window alert for GPS permission
    public void showSettingsAlert(){
        try {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
            alertDialog.setTitle("GPS Desactivado o sin permisos.");
            alertDialog.setMessage("Esta AplicaciĆ³n necesita el GPS para su correcto funcionamiento, debes habilitarlo y/o otorgar los permisos.¿Deseas abrir el Menu de Ajustes?");
            alertDialog.setPositiveButton("Ajustes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int which) {
                    dialog.dismiss();
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                    Activity activity = (Activity) mContext;
                    activity.finishAffinity();
                }
            });
            alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.w(_TAG,"El usuario ha cancelado");
                    dialog.cancel();
                    Activity activity = (Activity) mContext;
                    activity.finishAffinity();
                }
            });
            alertDialog.setCancelable(false);
            alertDialog.show();
        }catch (Exception e){
            Log.e(_TAG,"Error al mandar ventana");
        }
    }

    // Verify if GPS is enabled
    private boolean isGpsEnabled(){
        boolean isEnabled = true;
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
        try {
            if(locationManager != null) {
                isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return isEnabled;
    }

    /*from interfaces ConnectionCallbacks */
    @Override
    public void onConnectionSuspended(int status){
        Log.w(_TAG, "GPS suspended");
        Toast.makeText(this.mContext ,"onConnectionSuspended()",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLocationChanged(Location location){
        if(location!=null){
            Log.w(_TAG, "Location changed:" );
            latitud = location.getLatitude();
            longitud = location.getLongitude();
            //Toast.makeText(this.mContext ,"Getting new coordenates: Latitude : "+ latitud+" , Longitude : "+longitud ,Toast.LENGTH_LONG).show();
            Log.w(_TAG, "Getting new coordenates: Latitude : "+ latitud+" , Longitude : "+longitud );
        }
    }

    /* from interfaces from Sevice */
    @Override
    public IBinder onBind(Intent arg0){
        return null;
    }

}



Step 3

Implement into your activities

      import mx.com.yourAppName.Globals.GpsService;
            
      GpsService mGoogleGps = new GpsService( yourcontext );
     
      // Yoy can save and use wherever you want
        latitud = "" + String.valueOf(mGoogleGps.getLatitud());
        longitud = "" + String.valueOf(mGoogleGps.getLongitud());
       



References:

https://developer.android.com/training/location/
https://developer.android.com/guide/topics/location/strategies

Comments

Popular posts from this blog

Add image from URL

Retriving Android API version by code