Get My Concluding Known Location, Past Times Calling Locationservices.Fusedlocationapi.Getlastlocation()

Posted on

The instance demonstrate how to get my Last Known Location, yesteryear calling LocationServices.FusedLocationApi.getLastLocation() of Google play Service.


reference: Android Developers – Getting the Last Known Location

To purpose Google Play Service inwards your project, yous convey to Add Google Play Services to Android Studio project, lift final post.

MainActivity.java

package com.blogspot.android_er.androidgetlastlocation;  import android.location.Location; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast;  import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices;  populace shape MainActivity extends AppCompatActivity         implements GoogleApiClient.ConnectionCallbacks,         GoogleApiClient.OnConnectionFailedListener {      Button btnGetLastLocation;     TextView textLastLocation;      GoogleApiClient mGoogleApiClient;     Location mLastLocation;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         btnGetLastLocation = (Button) findViewById(R.id.getlastlocation);         btnGetLastLocation.setOnClickListener(btnGetLastLocationOnClickListener);         textLastLocation = (TextView) findViewById(R.id.lastlocation);          // Create an event of GoogleAPIClient.         if (mGoogleApiClient == null) {             mGoogleApiClient = novel GoogleApiClient.Builder(this)                     .addConnectionCallbacks(this)                     .addOnConnectionFailedListener(this)                     .addApi(LocationServices.API)                     .build();         }     }      View.OnClickListener btnGetLastLocationOnClickListener = novel View.OnClickListener() {         @Override         populace void onClick(View v) {              if(mGoogleApiClient != null){                 if(mGoogleApiClient.isConnected()){                     getMyLocation();                 }else{                     Toast.makeText(MainActivity.this,                             "!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();                 }             }else{                 Toast.makeText(MainActivity.this,                         "mGoogleApiClient == null", Toast.LENGTH_LONG).show();             }         }     };      person void getMyLocation(){         try{             /* code should explicitly cheque to run into if permission is available             (with 'checkPermission') or explicitly handgrip a potential 'SecurityException'              */             mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);             if (mLastLocation != null) {                 textLastLocation.setText(                         String.valueOf(mLastLocation.getLatitude()) + "\n"                                 + String.valueOf(mLastLocation.getLongitude()));                 Toast.makeText(MainActivity.this,                         String.valueOf(mLastLocation.getLatitude()) + "\n"                                 + String.valueOf(mLastLocation.getLongitude()),                         Toast.LENGTH_LONG).show();             }else{                 Toast.makeText(MainActivity.this,                         "mLastLocation == null",                         Toast.LENGTH_LONG).show();             }         } choose get got of (SecurityException e){             Toast.makeText(MainActivity.this,                     "SecurityException:\n" + e.toString(),                     Toast.LENGTH_LONG).show();         }     }      @Override     protected void onStart() {         mGoogleApiClient.connect();         super.onStart();     }      @Override     protected void onStop() {         mGoogleApiClient.disconnect();         super.onStop();     }      @Override     populace void onConnected(@Nullable Bundle bundle) {         getMyLocation();     }      @Override     populace void onConnectionSuspended(int i) {         Toast.makeText(MainActivity.this,                 "onConnectionSuspended: " + String.valueOf(i),                 Toast.LENGTH_LONG).show();     }      @Override     populace void onConnectionFailed(@NonNull ConnectionResult connectionResult) {         Toast.makeText(MainActivity.this,                 "onConnectionFailed: \n" + connectionResult.toString(),                 Toast.LENGTH_LONG).show();     } }  

layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:padding="16dp"     android:orientation="vertical"     tools:context="com.blogspot.android_er.androidgetlastlocation.MainActivity">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="center_horizontal"         android:autoLink="web"         android:text="https://rootandroid.org//"         android:textStyle="bold" />      <Button         android:id="@+id/getlastlocation"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Get my final location"/>      <TextView         android:id="@+id/lastlocation"         android:layout_width="match_parent"         android:layout_height="wrap_content"/> </LinearLayout>  

Permission:
Add uses-permission of ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION inwards your AndroidManifest.xml. In this example, I purpose ACCESS_FINE_LOCATION. (Read remark below most getLastLocation() supply null)


remark: getLastLocation() supply null!
– When run on existent device, ASUS Zenfone two running Android 5.0:
According to Android Developers – Getting the Last Known Location, yous tin sack add together permission of ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION. But inwards my trial, if add together permission of ACCESS_COARSE_LOCATION, getLastLocation() supply zip mostly, only about two success inwards to a greater extent than than thirty try. if add together permission of ACCESS_FINE_LOCATION, it almost success every time.


Next:
Requesting Permissions of Manifest.permission.ACCESS_FINE_LOCATION at Run Time

Related:
– Request Location Updates amongst LocationListener.onLocationChanged()