Get Current Location Android -No GPS and Internet

FrugalisMinds

Author - FrugalisMinds

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 .

  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:-_

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

//pagead2.googlesyndication.com/pagead/js/adsbygoogle

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

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

//pagead2.googlesyndication.com/pagead/js/adsbygoogle

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.

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());

          }
        }
      });
  }

}

//pagead2.googlesyndication.com/pagead/js/adsbygoogle

Download Source Code

[embed]https://www.youtube.com/watch?v=OmJKZgkBUZ8\[/embed\]

Deploy React JS in Tomcat

Spring Boot Jersey Example