Requesting Permissions Of Manifest.Permission.Access_Fine_Location At Function Time

Posted on

Refer to lastly illustration of “Get my Last Known Location, past times calling LocationServices.FusedLocationApi.getLastLocation()” inward Android Studio, you lot volition live prompted amongst “code should explicitly banking company gibe to meet if permission is available (with ‘checkPermission’) or explicitly handgrip a potential ‘SecurityException’” on the code “LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)”.

Last illustration handgrip ‘SecurityException’ amongst try/catch. This illustration present around other approach to check if permission is available amongst ‘checkPermission’, as well as thus call ActivityCompat.requestPermissions() if need, as well as handgrip the user respond in onRequestPermissionsResult().

reference: Android Developers – Requesting Permissions at Run Time


notice for sending place to Android Emulator: I bring to opened upward around other app, Google Maps, to monitor location, otherwise my illustration cannot larn the updated location.

Edit MainActivity.java from last post.

package com.blogspot.android_er.androidgetlastlocation;  import android.Manifest; import android.content.pm.PackageManager; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; 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;  world aeroplane MainActivity extends AppCompatActivity         implements GoogleApiClient.ConnectionCallbacks,         GoogleApiClient.OnConnectionFailedListener {      Button btnGetLastLocation;     TextView textLastLocation;      GoogleApiClient mGoogleApiClient;     Location mLastLocation;      static lastly int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;      @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 instance 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         world 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();             }         }     };      /*     // Handle 'SecurityException' amongst try/catch     somebody void getMyLocation(){         try{             //code should explicitly banking company gibe to meet 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();             }         } pick out get got of (SecurityException e){             Toast.makeText(MainActivity.this,                     "SecurityException:\n" + e.toString(),                     Toast.LENGTH_LONG).show();         }     }     */       //------------------------------------------------------------------------------     //ref: Requesting Permissions at Run Time     //http://developer.android.com/training/permissions/requesting.html     //------------------------------------------------------------------------------     somebody void getMyLocation() {         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             // hither to asking the missing permissions, as well as and thus overriding             //   world void onRequestPermissionsResult(int requestCode, String[] permissions,             //                                          int[] grantResults)             // to handgrip the illustration where the user grants the permission. See the documentation             // for ActivityCompat#requestPermissions for to a greater extent than details.               //------------------------------------------------------------------------------             ActivityCompat.requestPermissions(MainActivity.this,                     novel String[]{Manifest.permission.ACCESS_FINE_LOCATION},                     MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);              return;         }         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();         }     }      @Override     world void onRequestPermissionsResult(             int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {          switch (requestCode) {             illustration MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {                 // If asking is cancelled, the effect arrays are empty.                 if (grantResults.length > 0                         && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                     Toast.makeText(MainActivity.this,                             "permission was granted, :)",                             Toast.LENGTH_LONG).show();                     getMyLocation();                  } else {                     Toast.makeText(MainActivity.this,                             "permission denied, ...:(",                             Toast.LENGTH_LONG).show();                 }                 return;             }              // other 'case' lines to banking company gibe for other             // permissions this app powerfulness asking         }     }      @Override     protected void onStart() {         mGoogleApiClient.connect();         super.onStart();     }      @Override     protected void onStop() {         mGoogleApiClient.disconnect();         super.onStop();     }      @Override     world void onConnected(@Nullable Bundle bundle) {         getMyLocation();     }      @Override     world void onConnectionSuspended(int i) {         Toast.makeText(MainActivity.this,                 "onConnectionSuspended: " + String.valueOf(i),                 Toast.LENGTH_LONG).show();     }      @Override     world void onConnectionFailed(@NonNull ConnectionResult connectionResult) {         Toast.makeText(MainActivity.this,                 "onConnectionFailed: \n" + connectionResult.toString(),                 Toast.LENGTH_LONG).show();     } }  

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