Friday, 16 July 2021

Android Studio - Get Current Latitude And Longitude

1. Add this dependencies in your gradle file

    implementation 'com.google.android.gms:play-services-location:18.0.0'

2. Add this permission into your Manifest file


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

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


Simple UI to show your Location

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:gravity="center"

    tools:context=".MainActivity">


    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Latitude: "

        android:id="@+id/tv_lat"

        android:textSize="20sp"

        android:layout_marginBottom="10dp"

        android:textFontWeight="@integer/material_motion_duration_long_1"/>

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Longitude: "

        android:id="@+id/tv_long"

        android:textSize="20sp"

        android:textFontWeight="@integer/material_motion_duration_long_1"/>

</LinearLayout>


MainActivity  Class



public class MainActivity extends AppCompatActivity {

//    Todo: 4. Java Class Or MainActivity class

    //Todo: FusedLocationProviderClient
    FusedLocationProviderClient fusedLocationProviderClient;
    TextView tv_lat, tv_long;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
        tv_lat = (TextView) findViewById(R.id.tv_lat);
        tv_long = (TextView) findViewById(R.id.tv_long);

        //Todo: Check permission is granded or not
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            getCurrentLocation();
        } else {
//            Todo: If not then ask to tack location permission
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
            }, 100);
        }
    }
    //Todo: Trace Location Permission is granded or not
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100 && grantResults.length > 0 && (grantResults[0] + grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
            getCurrentLocation();
        } else {
            //Todo: If NOt Show a message
            Toast.makeText(MainActivity.this, "Can't trace your location", Toast.LENGTH_LONG).show();
        }
    }

    //Todo: GetCurrentLocationMethod To Get Current Cordinates
    @SuppressLint("MissingPermission")
    private void getCurrentLocation() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

            fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
                @Override
                public void onComplete(@NonNull Task<Location> task) {
                    Location location = task.getResult();
                    if (location != null) {
                        tv_lat.setText("Latitude: " +String.valueOf(location.getLatitude()));
                        tv_long.setText("Longitude: "+String.valueOf(location.getLongitude()));
                    } else {
                        LocationRequest locationRequest = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                                .setInterval(10000)
                                .setFastestInterval(1000)
                                .setNumUpdates(1);
                        LocationCallback locationCallback = new LocationCallback() {
                            @Override
                            public void onLocationResult(@NonNull LocationResult locationResult) {
                                super.onLocationResult(locationResult);
                                Location location1 = locationResult.getLastLocation();
                                tv_lat.setText("Latitude: " +String.valueOf(location.getLatitude()));
                                tv_long.setText("Longitude: "+String.valueOf(location.getLongitude()));
                            }
                        };
                        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
                        }

                    }
                }
            });
        } else {
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).
                    setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    }
}


Android Studio - Get Current Latitude And Longitude

1. Add this dependencies in your gradle file     implementation 'com.google.android.gms:play-services-location:18.0.0' 2. Add this p...