Sunday, July 25, 2021

How to Get Current Location In Android

It is necessary to find current location in android studio programmatically when you are developing location-based applications.

Globally, the location of any object is found in terms of the latitude and longitude.

For example, if you want to find restaurants near by you, you need your current gps location latitude and longitude.

With the help of latitude and longitude, you will be able to find location regardless of how far the object is from you.

How to Get Current Location In Android

In current GPS location android example tutorial, you will learn to get current latitude and longitude of Android device.

We will use Google’s FusedLocationAPI for getting current location with latitude and longitude.

Step 1.  Create a new project in Android Studio.

Make a fresh new project in Android Studio. Make sure you have select Empty activity as a Main Activity while creating a new project.

Step 2. Update build.gradle(Module:app) file

Add below source code in build.gradle(Module:app)

compile 'com.google.android.gms:play-services:11.8.0'

We need to use google’s play services to accomplish our task of getting current latitude and longitude.

Above line will import all the necessary classes from google api.

Step 3. Implement necessary interfaces

These interfaces are required.

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener

Step 4. Declare instances:

Declare Necessary statements as per below source code.

private GoogleApiClient mGoogleApiClient;

private Location mLocation;

private LocationManager mLocationManager;

private LocationRequest mLocationRequest;

Step 5.  Put following in onCreate() method

Update your onCreate() method as per following:

mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));

        mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));

        mGoogleApiClient = new GoogleApiClient.Builder(this)

                .addConnectionCallbacks(this)

                .addOnConnectionFailedListener(this)

                .addApi(LocationServices.API)

                .build();

        mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

 Step 6.  Last but not least, put required permissions in AndroidManifest.xml

Below two permissions are must to get desired results.

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

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

AndroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.exampledemo.parsaniahardik.gpsdemocode">

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

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

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

</manifest>

build.gradle(Module:app)

apply plugin: 'com.android.application'

android {

    compileSdkVersion 23

    buildToolsVersion "23.0.3"

    defaultConfig {

        applicationId "com.exampledemo.parsaniahardik.gpsdemocode"

        minSdkVersion 16

        targetSdkVersion 23

        versionCode 1

        versionName "1.0"

    }

    buildTypes {

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }

    }

}

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])

    testCompile 'junit:junit:4.12'

    compile 'com.android.support:appcompat-v7:23.4.0'

    compile 'com.google.android.gms:play-services:9.0.2'

}

activity_main.xml

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

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin"

    tools:context=".MainActivity">

    <TextView

        android:id="@+id/latitude"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentLeft="true"

        android:layout_alignParentTop="true"

        android:text="Latitude:"

        android:textSize="18sp" />

    <TextView

        android:id="@+id/latitude_textview"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignBaseline="@+id/latitude"

        android:layout_marginLeft="10dp"

        android:layout_toRightOf="@+id/latitude"

        android:textSize="16sp" />

    <TextView

        android:id="@+id/longitude"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentLeft="true"

        android:layout_alignParentTop="true"

        android:text="Longitude:"

        android:layout_marginTop="24dp"

        android:textSize="18sp" />

    <TextView

        android:id="@+id/longitude_textview"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignBaseline="@+id/longitude"

        android:layout_marginLeft="10dp"

        android:layout_toRightOf="@+id/longitude"

        android:textSize="16sp"/>

</RelativeLayout>

In the above layout file, I have used four TextViews. Two are static which will give you reference about which digit is latitude and which is other.

Other two textview represents the location factors and will be changed frequently.

Source snippet for the MainActivity.java file.

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private static final String TAG = "MainActivity";

    private TextView mLatitudeTextView;

    private TextView mLongitudeTextView;

    private GoogleApiClient mGoogleApiClient;

    private Location mLocation;

    private LocationManager mLocationManager;

    private LocationRequest mLocationRequest;

    private com.google.android.gms.location.LocationListener listener;

    private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */

    private long FASTEST_INTERVAL = 2000; /* 2 sec */

    private LocationManager locationManager;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));

        mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));

        mGoogleApiClient = new GoogleApiClient.Builder(this)

                .addConnectionCallbacks(this)

                .addOnConnectionFailedListener(this)

                .addApi(LocationServices.API)

                .build();

        mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

        checkLocation(); //check whether location service is enable or not in your  phone

    }

    @Override

    public void onConnected(Bundle bundle) {

        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;

        }

        startLocationUpdates();

        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if(mLocation == null){

            startLocationUpdates();

        }

        if (mLocation != null) {

            // mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));

            //mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));

        } else {

            Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();

        }

    }

    @Override

    public void onConnectionSuspended(int i) {

        Log.i(TAG, "Connection Suspended");

        mGoogleApiClient.connect();

    }

    @Override

    public void onConnectionFailed(ConnectionResult connectionResult) {

        Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());

    }

    @Override

    protected void onStart() {

        super.onStart();

        if (mGoogleApiClient != null) {

            mGoogleApiClient.connect();

        }

    }

    @Override

    protected void onStop() {

        super.onStop();

        if (mGoogleApiClient.isConnected()) {

            mGoogleApiClient.disconnect();

        }

    }

    protected void startLocationUpdates() {

        // Create the location request

        mLocationRequest = LocationRequest.create()

                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)

                .setInterval(UPDATE_INTERVAL)

                .setFastestInterval(FASTEST_INTERVAL);

        // Request location updates

        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;

        }

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,

                mLocationRequest, this);

        Log.d("reque", "--->>>>");

    }

    @Override

    public void onLocationChanged(Location location) {

        String msg = "Updated Location: " +

                Double.toString(location.getLatitude()) + "," +

                Double.toString(location.getLongitude());

        mLatitudeTextView.setText(String.valueOf(location.getLatitude()));

        mLongitudeTextView.setText(String.valueOf(location.getLongitude() ));

        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

        // You can now create a LatLng Object for use with maps

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

    }

    private boolean checkLocation() {

        if(!isLocationEnabled())

            showAlert();

        return isLocationEnabled();

    }

    private void showAlert() {

        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);

        dialog.setTitle("Enable Location")

                .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +

                        "use this app")

                .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

                        startActivity(myIntent);

                    }

                })

                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                    }

                });

        dialog.show();

    }

    private boolean isLocationEnabled() {

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

        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||

                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    }

}


No comments:

Post a Comment