Get Current Location Android -No GPS and Internet

Get Current Location Android -No GPS and Internet:-

Get Current Location Android – No Gps and Internet, There are different ways by which we can get users current location in android.Get Current Location Android no GPS and Internet, we are using   FusedLocationProviderClient . Its a battery efficient API introduced by Google.Using devices multiple sensors in a best possible way to is the ideal advantage of this API.Let’s go ahead and start .

Create Project:
Go to File->Create New project . Then add a location-based play-services-location dependency in your app.gradle .

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
  })

  compile 'com.android.support:design:25.3.1'
  compile 'com.android.support:appcompat-v7:25.3.1'
  compile 'com.android.support.constraint:constraint-layout:1.0.2'
  compile 'com.google.android.gms:play-services-location:11.0.0'

Create activity_main.xml:-

<?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"
  tools:context="com.example.sanju.locationexamplew.MainActivity">

  <TextView
    android:id="@+id/latitude_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginStart="10dp"
    android:textIsSelectable="true" />

  <TextView
    android:id="@+id/longitude_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="12dp"
    android:textIsSelectable="true" />

</LinearLayout>

Update manifest.xml with following permissions:-



We need users permission to access users device and the permissions are of two types .We are taking both permissions.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.sanju.locationexamplew">
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    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>

Now Add the following piece of Code in MainActivity.java




MainActivity.java:-

Once user permission is given we get device location and show on UI.But if a user rejects the app asking permisiions we again re-prompt user to provide permission. Now if the user selects checkbox Do not Ask again then we redirect the user to app settings page and let him provide permission.

package com.example.sanju.locationexamplew;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {

  protected Location mLastLocation;

  private String mLatitudeLabel;
  private String mLongitudeLabel;
  private TextView mLatitudeText;
  private TextView mLongitudeText;
  private FusedLocationProviderClient mFusedLocationClient;

  private static final String TAG = MainActivity.class.getSimpleName();

  private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;

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

    mLatitudeLabel = "latitude";
    mLongitudeLabel = "longitude";
    mLatitudeText = (TextView) findViewById((R.id.latitude_text));
    mLongitudeText = (TextView) findViewById((R.id.longitude_text));

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

  }

  @Override
  public void onStart() {
    super.onStart();

    if (!checkPermissions()) {
      requestPermissions();
    } else {
      getLastLocation();
    }
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                         @NonNull int[] grantResults) {
    Log.i(TAG, "onRequestPermissionResult");
    if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
      if (grantResults.length <= 0) {
        // If user interaction was interrupted, the permission request is cancelled and you
        // receive empty arrays.
        Log.i(TAG, "User interaction was cancelled.");
      } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // Permission granted.
        getLastLocation();
      } else {
        // Permission denied.

        // Notify the user via a SnackBar that they have rejected a core permission for the
        // app, which makes the Activity useless. In a real app, core permissions would
        // typically be best requested during a welcome-screen flow.

        // Additionally, it is important to remember that a permission might have been
        // rejected without asking the user for permission (device policy or "Never ask
        // again" prompts). Therefore, a user interface affordance is typically implemented
        // when permissions are denied. Otherwise, your app could appear unresponsive to
        // touches or interactions which have required permissions.
        showSnackbar(R.string.textwarn, R.string.settings,
          new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              // Build intent that displays the App settings screen.
              Intent intent = new Intent();
              intent.setAction(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
              Uri uri = Uri.fromParts("package",
                BuildConfig.APPLICATION_ID, null);
              intent.setData(uri);
              intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              startActivity(intent);
            }
          });
      }
    }
  }

  private void showSnackbar(final int mainTextStringId, final int actionStringId,
                            View.OnClickListener listener) {
    Snackbar.make(findViewById(android.R.id.content),
      getString(mainTextStringId),
      Snackbar.LENGTH_INDEFINITE)
      .setAction(getString(actionStringId), listener).show();
  }

  private boolean checkPermissions() {
    int permissionState = ActivityCompat.checkSelfPermission(this,
      Manifest.permission.ACCESS_FINE_LOCATION);
    return permissionState == PackageManager.PERMISSION_GRANTED;
  }

  private void startLocationPermissionRequest() {
    ActivityCompat.requestPermissions(MainActivity.this,
      new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
      REQUEST_PERMISSIONS_REQUEST_CODE);
  }

  private void requestPermissions() {
    boolean shouldProvideRationale =
      ActivityCompat.shouldShowRequestPermissionRationale(this,
        Manifest.permission.ACCESS_FINE_LOCATION);

    // Provide an additional rationale to the user. This would happen if the user denied the
    // request previously, but didn't check the "Don't ask again" checkbox.
    if (shouldProvideRationale) {
      Log.i(TAG, "Displaying permission rationale to provide additional context.");

      showSnackbar(R.string.textwarn, android.R.string.ok,
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            // Request permission
            startLocationPermissionRequest();
          }
        });

    } else {
      Log.i(TAG, "Requesting permission");
      // Request permission. It's possible this can be auto answered if device policy
      // sets the permission in a given state or the user denied the permission
      // previously and checked "Never ask again".
      startLocationPermissionRequest();
    }
  }

  private void getLastLocation() {
    mFusedLocationClient.getLastLocation()
      .addOnCompleteListener(this, new OnCompleteListener<Location>() {
        @Override
        public void onComplete(@NonNull Task<Location> task) {
          if (task.isSuccessful() && task.getResult() != null) {
            mLastLocation = task.getResult();

            mLatitudeText.setText(String.format(Locale.ENGLISH, "%s: %f",
              mLatitudeLabel,
              mLastLocation.getLatitude()));
            mLongitudeText.setText(String.format(Locale.ENGLISH, "%s: %f",
              mLongitudeLabel,
              mLastLocation.getLongitude()));
          } else {
            Log.w(TAG, "getLastLocation:exception", task.getException());

          }
        }
      });
  }

}




Download Source Code

Deploy React JS in Tomcat

Spring Boot Jersey Example