Android App Development With AndroidCource: March 2018

Saturday, 31 March 2018

How to get the current location latitude and longitude in android

Step 1

Add Manifest Permission

   
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera2" />

Step 2

MainActivity.xml Code here

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="com.bhaumik.currentlatlong.MainActivity">


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="31dp"
        android:layout_marginStart="31dp"
        android:layout_marginTop="49dp"
        android:text="Latitude"
        android:textSize="22dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:layout_below="@+id/textView"
        android:layout_marginTop="35dp"
        android:text="Longitude"
        android:textSize="22dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_lat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView2"
        android:layout_marginLeft="86dp"
        android:layout_marginStart="86dp"
        android:layout_toEndOf="@+id/textView2"
        android:layout_toRightOf="@+id/textView2"
        android:textSize="19dp" />

    <TextView
        android:id="@+id/tv_long"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView2"
        android:layout_marginLeft="58dp"
        android:layout_marginStart="58dp"
        android:layout_toEndOf="@+id/textView2"
        android:layout_toRightOf="@+id/textView2"
        android:textSize="19dp" />
</RelativeLayout>

Step 3

MainActivity.java Code Here

package com.bhaumik.currentlatlong;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements LocationListener{

    TextView tv_lat,tv_long;

    LocationManager locationManager;
    public static final int PERMISSION_CODE = 100;
    LocationListener locationListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_lat = findViewById(R.id.tv_lat);
        tv_long = findViewById(R.id.tv_long);

        if (!checkPermission()){
            requestPermission();
        }


        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        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;
        }

        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,50,1,this);

    }

    public boolean checkPermission(){

        int result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);
        int result1 = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);

        return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;

    }

    public void requestPermission(){

        ActivityCompat.requestPermissions(MainActivity.this,new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
        },PERMISSION_CODE);


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode){

            case PERMISSION_CODE :

                if (grantResults.length > 0){

                    boolean location = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean location1 = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                    if (location){

                        Toast.makeText(this, "Permission Granted..", Toast.LENGTH_SHORT).show();
                    }else{

                        Toast.makeText(this, "Permission Denied..", Toast.LENGTH_SHORT).show();

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

                            if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)){

                                showMsg("You need to allow access to the Permission", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                                            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_CODE);
                                        }
                                    }
                                });
                                return;
                            }
                        }
                    }
                }
        }
    }

    private void showMsg(String s, DialogInterface.OnClickListener onClickListener) {

        new AlertDialog.Builder(MainActivity.this)
                .setMessage(s)
                .setPositiveButton("OK",onClickListener)
                .setNegativeButton("Cancel",null)
                .create()
                .show();

    }

    @Override
    public void onLocationChanged(Location location) {

        tv_lat.setText("" + location.getLatitude());
        tv_long.setText("" + location.getLongitude());

        Log.d("tag","Latitude -> " + location.getLatitude());
        Log.d("tag","Longitude -> " + location.getLongitude());
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}


OutPut