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

How to call Post API using Retrofit in Android using Jetpack Compose?

Note: If you are seeking Java code for Jetpack Compose , please note that Jetpack Compose is only available in Kotlin . It uses features such as coroutines , and the handling of @Composable annotations is handled by a Kotlin compiler. There is no method for Java to access these. Therefore, you cannot use Jetpack Compose if your project does not support Kotlin. Step By Step Implementation Step 1: Create a New Project in Android Studio We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. Step 2: Add the below dependency to 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 AndroidManifes...

How to make a 'SET SELECTION' in spinner if you have a model type array list data in android kotlin?

 //if a have a value like 'Item 3' need to set selection   val spinnerItemValue="Item 3"//some country name //find the index of the item with the target text val position = arrayList!!.indexOfFirst { it.countryName(//Note: model key which store the country   name for spinner dorp-down)==spinnerItemValue}  //set the selection in the spinner  if(position>=0){       //if you user data binding in your project        binding.countrySpinner.setSelection(position)     //if you use findViewById() in your project       Spinner countrySpinner=findViewById(R.id.countrySpinner)       countrySpinner.setSelection(position) }

Retrofit 2 — Receive Plain-String Responses

Android apps usually interact with REST APIs, which often use JSON as a data format. We've focused almost all of our tutorials on sending JSON or XML requests, and converting JSON or XML responses. Scalars Converter for Plain Strings To receive plain-text or plain-string responses you can utilize the scalars converter. You can integrate the converter by adding it as a dependency to your app's build.gradle: dependencies {       implementation 'com.squareup.retrofit2:retrofit:2.9.0'     implementation 'com.squareup.retrofit2:converter-gson:2.9.0'     implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'//You need to add this     implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2' } Next, you need to describe the endpoint you want to interact with. In this demo case, you'll use a GET request with the dynamic URL feature to pass any URL to the method, and set the response type as String. @GET() Call<String...