Skip to main content

Location Using Fuse Library in Android

 Step-1: Add All Required Dependencies

    //fuse library
    implementation 'com.google.android.gms:play-services-location:19.0.1'
    implementation 'com.google.android.gms:play-services-drive:17.0.0'

Step-2: Add All Required Permissions in AndroidManifest File

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Step-3: Make activity_main.xml file for show location

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable
            name="viewBinding"
            type="com.vimal.locationusingfuselibrary.MainActivity" />
    </data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvLatLong"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvLatLongOnLocationChange"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_marginTop="15dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvLatLong" />

</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Step-4: Make MainActivity.kt file and Past below code

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.location.Location
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
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
import com.vimal.locationusingfuselibrary.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity(), GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private lateinit var binding: ActivityMainBinding
    //for location GPS
    private var mGoogleApiClient: GoogleApiClient? = null
    private var mLocationRequest: LocationRequest? = null
    var mLastLocation: Location? = null
    var altitude: String? = null
    private var latitude: String? = null
    private var longitude: String? = null
    private var isGPS = false
    private val REQUEST_PERMISSIONS = 20

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.viewBinding = this

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkLocationPermission()){
                getGPS()
            }
        }
    }

    private fun checkLocationPermission(): Boolean {
        val loc =ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
        val loc2 = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        val listPermissionsNeeded: MutableList<String> = ArrayList()
        if (loc2 != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }
        if (loc != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        }
        if (listPermissionsNeeded.isNotEmpty()) {
            ActivityCompat.requestPermissions(this,
                listPermissionsNeeded.toTypedArray<String>(),REQUEST_PERMISSIONS)
            return false
        }
        return true
    }

    private fun getGPS() {
        GpsUtils(this).turnGPSOn { isGPSEnable -> // turn on GPS
            isGPS = isGPSEnable
        }
        buildGoogleApiClient()
    }

    @Synchronized
    fun buildGoogleApiClient() {
        mGoogleApiClient = GoogleApiClient.Builder(this)
            .addConnectionCallbacks((this as GoogleApiClient.ConnectionCallbacks))
            .addOnConnectionFailedListener((this as GoogleApiClient.OnConnectionFailedListener))
            .addApi(LocationServices.API)
            .build()
    }

    @SuppressLint("SetTextI18n")
    override fun onConnected(bundle: Bundle?) {
        mLocationRequest = LocationRequest.create()
        mLocationRequest!!.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        mLocationRequest!!.interval = 100 // Update location every second
        if (ActivityCompat.checkSelfPermission(
                this@MainActivity,
                Manifest.permission.ACCESS_FINE_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 as LocationListener)
        )
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient!!
        )
        if (mLastLocation != null) {
            latitude = mLastLocation!!.latitude.toString()
            longitude = mLastLocation!!.longitude.toString()
            altitude = mLastLocation!!.altitude.toString()
            Log.e("LAT", "onConnected: $latitude")
            Log.e("LONG", "onConnected: $longitude")
            Log.e("ALTI", "onConnected: $altitude")

            binding.tvLatLong.text = "Lat-Long\n$latitude\n$longitude"
        }
    }

    override fun onConnectionSuspended(i: Int) {}

    @SuppressLint("SetTextI18n")
    override fun onLocationChanged(location: Location) {
        latitude = location.latitude.toString()
        longitude = location.longitude.toString()
        println("latitude>>>>$latitude")

        binding.tvLatLongOnLocationChange.text = "On Location change Lat-Long\n$latitude\n$longitude"

        altitude = location.altitude.toString()
        //String Address=cf.getAddress(Double.parseDouble(latitude), Double.parseDouble(longitude));
        val pref = applicationContext.getSharedPreferences(
            "GCMSetting",
            MODE_PRIVATE
        ) // 0 - for private mode
        val editor = pref.edit()
        editor.putString("LATTITUDE>>>", latitude)
        editor.putString("LONGITUDE>>>", longitude)
        editor.putString("ALTITUDE>>>", altitude)

        Log.e("LAT", "onLocationChanged: $latitude")
        Log.e("LONG", "onLocationChanged: $longitude")
        Log.e("ALTI", "onLocationChanged: $altitude")

        editor.commit() // commit changes
    }

    override fun onStart() {
        super.onStart()
        if (!mGoogleApiClient!!.isConnected) mGoogleApiClient!!.connect()
    }

    override fun onConnectionFailed(connectionResult: ConnectionResult) {}
}

Step-5: Make AppConstants class and Past Below code

public class AppConstants {
    public static final int GPS_REQUEST = 3033;
    public static final String APP_VERSION = "";
}

Step-6: Make GPSUtils class and Past below code

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.IntentSender;
import android.location.LocationManager;

import androidx.annotation.NonNull;

import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

public class GpsUtils {private final Context context;
    private final SettingsClient mSettingsClient;
    private final LocationSettingsRequest mLocationSettingsRequest;
    private final LocationManager locationManager;
    private final LocationRequest locationRequest;public GpsUtils(Context context) {
        this.context = context;
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        mSettingsClient = LocationServices.getSettingsClient(context);
        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(10 * 1000);
        locationRequest.setFastestInterval(2 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
        mLocationSettingsRequest = builder.build();//**************************
        builder.setAlwaysShow(true); //this is the key ingredient
        //**************************
    }// method for turn on GPS
    public void turnGPSOn(onGpsListener onGpsListener) {if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        if (onGpsListener != null) {
            onGpsListener.gpsStatus(true);
        }
    } else {
        mSettingsClient
                .checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener((Activity) context, new OnSuccessListener<LocationSettingsResponse>() {
                    @SuppressLint("MissingPermission")
                    @Override
                    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {//  GPS is already enable, callback GPS status through listener
                        if (onGpsListener != null) {
                            onGpsListener.gpsStatus(true);
                        }
                    }
                })
                .addOnFailureListener((Activity) context, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        int statusCode = ((ApiException) e).getStatusCode();
                        switch (statusCode) {
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:try {
                                // Show the dialog by calling startResolutionForResult(), and check the
                                // result in onActivityResult().
                                ResolvableApiException rae = (ResolvableApiException) e;
                                rae.startResolutionForResult((Activity) context, AppConstants.GPS_REQUEST);
                            } catch (IntentSender.SendIntentException sie) {
                              //  Log.i(TAG, "PendingIntent unable to execute request.");
                            }
                                break;
                            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                String errorMessage = "Location settings are inadequate, and cannot be " +
                                        "fixed here. Fix in Settings.";
                                //Log.e(TAG, errorMessage);Toast.makeText((Activity) context, errorMessage, Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }
    }public interface onGpsListener {
        void gpsStatus(boolean isGPSEnable);
    }
}

Comments

Popular posts from this blog

What is android?

  Android is a complete set of software for mobile devices such as tablet computers, notebooks, smartphones etc. Or We can say, android is a Linux-Based Operating System. It is currently used in various devices such as mobiles, tablets, televisions etc.

How to call Post type API using Retrofit in Android?

Step by Step Implementation Step 1: Create a New Project Step 2: Add the below dependency in your build.gradle file Navigate to the Gradle Scripts > build.gradle (Module:app) and add the below dependency in the dependencies section.  // below dependency for using the retrofit implementation ‘com.squareup.retrofit2:retrofit:2.9.0’ implementation ‘com.squareup.retrofit2:converter-gson:2.5.0’ After adding this dependency sync your project and now move towards the AndroidManifest.xml part.   Step 3: Adding permissions to the internet in the AndroidManifest.xml file Navigate to the app > AndroidManifest.xml and add the below code to it.  <!--permissions for INTERNET--> <uses-permission android:name="android.permission.INTERNET"/> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.  <?xml version="1.0"...

What is the Android Architecture?

 Well, Android Architecture is categorized into five part.     1. Linux kernel     2. Native Libraries (Middleware),     3. Android Runtime     4. Application Framework     5. Applications You can see the picture shown below. Linux kernel: It is the heart of android architecture that exists at the root of android architecture. Linux kernel is responsible for device drivers, power management, memory management, device management and resource access. Native Libraries: On the top of Linux kernel, their are Native libraries such as Web-Kit, Open-GL, Free-Type, SQLite, Media, C runtime library (libc) etc. The Web-Kit library is responsible for browser support, SQLite is for database, Free-Type for font support, Media for playing and recording audio and video formats. Android Runtime: In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run android application. DVM...