onActivityResult() is not called (MapFragment) - java

I am trying to make my map app redirect to the settings for location permissions and once permissions are granted redirect again to the app. for some reason my onActivityResult is not even called after starting the activity intent. and basically what happens is when I click on the snackbar action button that appears, it starts the settingsIntent and redirects me to the settings nicely but the activity isn't going for result state and the onActivityResult is never called
any suggestions?
here is the code:
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
private fun checkPermissions(): Boolean {
//returns true if granted permission for location
var checker = ActivityCompat.checkSelfPermission(
applicationContext,
android.Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
applicationContext,
android.Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
if (checker) {
Log.d(TAG, "granted Permissions")
} else {
Log.d(TAG, "no Permissions granted")
}
return checker
}
#RequiresApi(Build.VERSION_CODES.M)
private fun requestPermissions() {
requestPermissions(
arrayOf(
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION
), PERMISSION_ID
)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (!checkPermissions()) {
Snackbar.make(
map.view!!,
"Please Enable Location Permission",
Snackbar.LENGTH_INDEFINITE
).setAction("Enable Location",
View.OnClickListener {
var settingsIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivityForResult(settingsIntent, 1)
})
.show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Log.d(TAG, "Redirected to settings for Location Permissions ")
if (resultCode == Activity.RESULT_OK) {
if (checkPermissions()) {
Log.d(TAG, "Permissions granted from settings")
startActivity(Intent(this, MapsActivity::class.java))
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onCreate(savedInstanceState: Bundle?) {
Log.d(TAG, "onCreate called")
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
#RequiresApi(Build.VERSION_CODES.M)
override fun onMapReady(googleMap: GoogleMap) {
Log.d(TAG, "omMapReady:starts")
mMap = googleMap
requestPermissions()
}
}
manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.burgertracker">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<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">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

This is working for me,
MainActivity
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<TextView>(R.id.tv_click).setOnClickListener {
val settingsIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivityForResult(settingsIntent, 1)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Toast.makeText(this, "Hakuna Mattat", Toast.LENGTH_SHORT).show()
}
}
activity_main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<TextView
android:id="#+id/tv_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demointentapplication">
<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>
I navigate to Settings page when I click the TextView on MainActivity and when I press back from Settings page I see the Toast message Hakuna Mattat everytime.

there are some differences between our codes, your code is just on a regular activity and mine is on a mapActivity which has a map Fragment displayed.. i run the startActivityForResult from my onRequestPermissiosnResult function since i need to to run only if the permissions are not granted.. so i guess any of those must be the reason..
also i checked and the onActivityResult is called only when i press back once the location settings is displayed.. but the problem is that i need to click on the app in that location setting page and then allow location for it and if i do so and then press home button 2 times to go back the the app it does not go back and onActivityResult is not called..
so either i need to know if theres an option to start an intent that will start an activity that goes directly to my specific app location settings and then i guess it will work or either if i will know how to control that settings activity because once it moves to the settings the mapAcitivty is stopped..

int PERMISSION_ID = 44;
FusedLocationProviderClient mFusedLocationClient;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_home);
mFusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
}
private boolean checkPermissions() {
if (ActivityCompat.checkSelfPermission(HomeActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(HomeActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(
HomeActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_ID
);
}
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#SuppressLint("MissingPermission")
private void getLastLocation() {
if (checkPermissions()) {
if (isLocationEnabled()) {
mFusedLocationClient.getLastLocation().addOnCompleteListener(
new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
Geocoder geocoder = new Geocoder(HomeActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
assert addresses != null;
if (addresses != null) {
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
String[] arrOfStr = cityName.split(",");
locationTV.setText("You're in " + arrOfStr[arrOfStr.length - 2] + ", " + arrOfStr[arrOfStr.length - 1]);
}
}
}
}
);
} else {
Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
requestPermissions();
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_ID) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onResume() {
super.onResume();
if (checkPermissions()) {
getLastLocation();
}
}
#SuppressLint("MissingPermission")
private void requestNewLocationData() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(0);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.requestLocationUpdates(
mLocationRequest, mLocationCallback,
Looper.myLooper()
);
}
private LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
Geocoder geocoder = new Geocoder(HomeActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
assert addresses != null;
if (addresses != null) {
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
String[] arrOfStr = cityName.split(",");
locationTV.setText("You're in " + arrOfStr[arrOfStr.length - 2] + ", " +
arrOfStr[arrOfStr.length - 1]);
}
}
};

Related

File.listFiles() is returning null in android 11

I was creating an application to test whether File.listFiles() method is working or not. To check this I made an application and I used it there but this returning null in place of an array.
This is my full code please help and I have granted all permissions for android 11
MainActivity.java
package com.rajkumarcreations.file;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.File;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.os.Build.VERSION.SDK_INT;
public class MainActivity extends AppCompatActivity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.btn);
if(!checkPermission()){
requestPermission();
}else{
File file = new File(Environment.getExternalStorageDirectory()+"/Download/");
File[] allfiles = null;
allfiles = file.listFiles();
if(file.exists()){
tv.setText("Exist");
}
if(allfiles!=null){
Toast.makeText(this, "length is "+allfiles.length, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Array is null", Toast.LENGTH_SHORT).show();
}
}
}
private boolean checkPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
return Environment.isExternalStorageManager();
} else {
int write = ContextCompat.checkSelfPermission(MainActivity.this, WRITE_EXTERNAL_STORAGE);
int read = ContextCompat.checkSelfPermission(MainActivity.this, READ_EXTERNAL_STORAGE);
return write == PackageManager.PERMISSION_GRANTED && read == PackageManager.PERMISSION_GRANTED;
}
}
private void requestPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s",new Object[]{getApplicationContext().getPackageName()})));
startActivityForResult(intent, 2000);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 2000);
}
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 333);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2000) {
if (SDK_INT >= Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
Toast.makeText(this, "Allow permissions granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Allow permission for storage access!", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
if (requestCode==333){
if (grantResults.length > 0) {
boolean WRITE_EXTERNAL_STORAGE = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean READ_EXTERNAL_STORAGE = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (READ_EXTERNAL_STORAGE && WRITE_EXTERNAL_STORAGE) {
Toast.makeText(this, "All permissions granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Allow permission for storage access!", Toast.LENGTH_SHORT).show();
}
}
}
}
}
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rajkumarcreations.file">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:requestLegacyExternalStorage="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>
XML File
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/btn"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
According to your requirement you were trying to access list of files under a directory by using listfiles() method. And want check
it is working or not. But this returning null.
First, Declare the MANAGE_EXTERNAL_STORAGE permission in the manifest.
// For 30 and after
<uses-permission
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
// For before 30
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
tools:node="merge" />
<uses-permission
android:name="android.permission.STORAGE"
tools:node="merge" />
// For 30 and after
Second, Use the ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION intent
action to direct users to a system settings page where they can enable
the following option for your app: Allow access to manage all files.
Write the code on your onCreate Method:
if (Build.VERSION.SDK_INT < 30) {
if (!checkBefore30()) {
requestBefore30();
} else {
// User granted file permission, Access your file
readFiles();
}
} else if (Build.VERSION.SDK_INT >= 30) {
check30AndAfter();
} else {
// User already has file access permission
readFiles();
}
Write those methods on your Activity:
private boolean checkBefore30() {
return ContextCompat.checkSelfPermission(YourActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
private void requestBefore30() {
if(ActivityCompat.shouldShowRequestPermissionRationale(YourActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(LoginActivity.this, "Storage permission required. Please allow this permission", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(YourActivity.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
} else {
ActivityCompat.requestPermissions(YourActivity.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission for storage access successful!
// Read your files now
} else {
// Allow permission for storage access!
}
break;
}
}
#RequiresApi(api = Build.VERSION_CODES.R)
private void check30AndAfter() {
if (!Environment.isExternalStorageManager()) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
startActivityForResult(intent, 200);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 200);
}
}
}
#RequiresApi(api = Build.VERSION_CODES.R)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200) {
if (30 >= Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
// Permission for storage access successful!
// Read your files now
} else {
// Allow permission for storage access!
}
}
}
}
private void readFiles() {
File file;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
} else {
file = new File(Environment.getExternalStorageDirectory().toString() + "/Download/");
}
File[] files= null;
files= file.listFiles();
if (file.exists()) {
// files exist
}
if (allfiles != null) {
Toast.makeText(this, " file length is" + files.length, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No files", Toast.LENGTH_SHORT).show();
}
}
Hopefully your problem will be solved.
Try with the following code it's working.
//Add below permission in your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
//Add below attribute in manifest application tag
android:requestLegacyExternalStorage="true"
//Activity code, ask file read/write runtime permission
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
requestForPermission();
getFile();
}
private void getFile() {
File file;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
} else {
file = new File(Environment.getExternalStorageDirectory().toString() + "/Download/");
}
File[] allfiles = null;
allfiles = file.listFiles();
if (file.exists()) {
tv.setText("Exist");
}
if (allfiles != null) {
Toast.makeText(this, "length is " + allfiles.length, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Array is null", Toast.LENGTH_SHORT).show();
}
}
private void requestForPermission() {
ActivityCompat.requestPermissions(
this,
new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
},
101
);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 101:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getFile();
} else {
//not granted
}
break;
default:
break;
}
}
}

GeofenceClient.addGeofences() doesn't start IntentService

I'm trying to use google's geofences and I follow the google docs
The problem is that when I call addGeofences() it should start the IntentService but it just stopped.
The addGeofences() result always shows success and my Log:
and then nothing happens,
my IntentService's onHandleIntent()'s Log shows nothing; I think it's not even activated.
I used Nexus5 API25 emulator and Target Android7.1.1(Google APIs)for testing.
I searched much but still can't figure out why; maybe I missed something.
here is my code:
private void startGeofenceMonitor()
{
Log.i("info", "Start geofence monitoring");
try
{
int permission = ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION);
if (permission != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions( MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION} , PERMISSIONS_REQUEST_CODE);
Log.i("info", "Permission not available! ");
}
else
{
mGeofencingClient = LocationServices.getGeofencingClient(this);
geofenceList.add(new Geofence.Builder().setRequestId("point0")
.setCircularRegion(55, 55, 15)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setNotificationResponsiveness(1000)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent())
.addOnSuccessListener(this, new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
Log.i("info", "geofence added!: ");
}
})
.addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
Log.i("info", "geofence failed! " + e.toString());
}
});
}
}
catch (Exception e)
{
Log.i("er", e.getMessage());
}
}
private GeofencingRequest getGeofencingRequest()
{
return new GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_DWELL)
.addGeofences(geofenceList)
.build();
}
private PendingIntent getGeofencePendingIntent()
{
if (mGeofencePendingIntent != null)
{
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
mGeofencePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return mGeofencePendingIntent;
}
and my IntentSrvice
public GeofenceTransitionsIntentService()
{
super("GeofenceTransitionsIntentService");
Log.i("info", "IntentService is activated!");
}
#Override
protected void onHandleIntent(Intent intent)
{
String test = intent.getStringExtra("pls");
Log.i("info", "onHandleIntent is activated!");
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
Log.i("info", "geofencingEvent size: " + intent.toString());
if (geofencingEvent.hasError())
{
Log.e("er", "geofencingEvent has error!");
return;
}
else
{
}
int geofenceTransition = geofencingEvent.getGeofenceTransition();
Log.e("er", "geofenceTransition" + geofenceTransition);
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER)
{
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
Geofence geofence = triggeringGeofences.get(0);
String requestID = geofence.getRequestId();
Log.i("geo", "Entering geofence : " + requestID);
}
else if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT)
{
Log.i("geo", "Exiting geofence : ");
}
else
{
Log.i("geo", "geo not in range ");
}
}
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hs.geofencestest">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<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>
<service android:name=".GeofenceTransitionsIntentService" android:exported="true"/>
</application>

Why permission dialog disappear when application is open again?

I have added READ_PHONE_STATE permission in my project.
Scenario:
I am just opening my application and I get Permission alert “Allow My Application to make and manage phone calls ?"
Now I am moving my application in background and again opening by tap on My Application icon
Result: “Allow My Application to make and manage phone calls ?" Permission pop up get disappears.
Can any one tell why this behaviour?
Note: I am using launchMode="singleInstance" and when using launchMode="standard" all is working fine.
Sharing my code :
<?xml version="1.0" encoding="utf-8"?>
<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" android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
public class MainActivity extends AppCompatActivity {
public static final Integer REQUEST_CODE_FOR_PERMISSION = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askForPermission(this, Manifest.permission.READ_PHONE_STATE, REQUEST_CODE_FOR_PERMISSION);
}
public static void askForPermission(Activity context, String permission, Integer requestCode) {
if ((Build.VERSION.SDK_INT >= 23) && (context != null) && (TextUtils.isEmpty(permission) == false)) {
ActivityCompat.requestPermissions(context, new String[]{permission}, requestCode);
}
}}
Based on singleTask behaviour
If an instance of the activity already exists in a separate task, the system routes the intent to the existing instance through a call to its onNewIntent() method, rather than creating a new instance.
https://developer.android.com/guide/components/activities/tasks-and-back-stack#TaskLaunchModes
I was able to fix this issue by handling the code in
onNewIntent(Intent intent)
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
askForPermission(this, Manifest.permission.READ_PHONE_STATE, REQUEST_CODE_FOR_PERMISSION);
}
Try this,
public class MainActivity extends AppCompatActivity {
public static final Integer REQUEST_CODE_FOR_PERMISSION = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#override
private void onResume(){
askForPermission(this, Manifest.permission.READ_PHONE_STATE, REQUEST_CODE_FOR_PERMISSION);
}
public static void askForPermission(Activity context, String permission, Integer requestCode) {
if ((Build.VERSION.SDK_INT >= 23) && (context != null) && (TextUtils.isEmpty(permission) == false)) {
ActivityCompat.requestPermissions(context, new String[]{permission}, requestCode);
}
}}
Call finish() in onBackPressed()
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
This will launch activity again and your code will work in onCreate()
Use Runtime Permission like this:
public class MainActivity extends Activity {
private static final int PERMISSION_REQUEST_CODE = 200;
Context context;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
activity = this;
setContentView(R.layout.activity_splash);
if (!checkPermission()) {
OpenActivity();
} else {
if (checkPermission()) {
requestPermissionAndContinue();
} else {
OpenActivity();
}
}
}
private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED;
}
private void requestPermissionAndContinue() {
if (ContextCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, READ_PHONE_STATE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("STORAGE permission is necessary to write event!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(SplashActivityANother.this, new String[]{READ_PHONE_STATE,
}, PERMISSION_REQUEST_CODE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
Log.e("", "permission denied, show dialog");
} else {
ActivityCompat.requestPermissions(this, new String[]{READ_PHONE_STATE
}, PERMISSION_REQUEST_CODE);
}
} else {
OpenActivity();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (permissions.length > 0 && grantResults.length > 0) {
boolean flag = true;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
flag = false;
}
}
if (flag) {
OpenActivity();
} else {
finish();
}
} else {
finish();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void OpenActivity() {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
}
}
and Add
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> in to menifist file.
Hope this Helps you

App has stopped when trying to open google map

I am working on a mobile application and I'm still new to Android Studio. In this app I need to use Google Maps. The app runs fine on my smartphone but when i click the button to navigate to the Google Map page, there is a pop up message that says my app has stopped. Can someone please help me troubleshoot this problem?
MapsActivity.java
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastlocation;
private Marker currentLocationMarker;
public static final int REQUEST_LOCATION_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
setUpMapIfNeeded();
}
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode)
{
case REQUEST_LOCATION_CODE:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission is granted
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if(client == null)
{
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else //permission is denied
{
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_LONG).show();
}
return;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
//DO WHATEVER YOU WANT WITH GOOGLEMAP
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//mMap.setMyLocationEnabled(true);
mMap.setTrafficEnabled(true);
mMap.setIndoorEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
setUpMap();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
SupportMapFragment mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
mMap.getMapAsync(this);
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(3.188426, 101.682027)).title("This is my first marker"));
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,
//
mMap.setMyLocationEnabled(true); //int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
}
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
#Override
public void onLocationChanged(Location location) {
// latitude = location.getLatitude();
//longiude = location.getLongitude();
lastlocation = location;
if (currentLocationMarker != null)
{
currentLocationMarker.remove();
}
LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(10));
if (client != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
/*#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}*/
public void onClick (View v)
{
if(v.getId() == R.id.searchbtn)
{
EditText userlocation = (EditText)findViewById(R.id.userLocation);
String location = userlocation.getText().toString();
List<Address> addressList = null;
MarkerOptions mo = new MarkerOptions();
if( !location.equals(""))
{
Geocoder geocoder = new Geocoder(this);
try
{
addressList = geocoder.getFromLocationName(location, 5);
}
catch (IOException e)
{
e.printStackTrace();
}
for(int i=0; i<addressList.size(); i++)
{
Address myAddress = addressList.get(i);
LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
mo.position(latLng);
mo.title("Your Search Result");
mMap.addMarker(mo);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
}
public boolean checkLocationPermission()
{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE);
}
return false;
}
else
return true;
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.asus.autocare">
<!-- To auto-complete the email text field in the login form with the user's
emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name =
"com.google.android.providers.gsf.permission.READ_GSERVICES" />
<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:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity" />
<activity android:name=".LoginActivity" />
<activity android:name=".RegisterActivity" />
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" />
<activity android:name=".ChooseActivity"></activity>
</application> </manifest>
This is the error that I got:
05-02 21:11:10.236 30445-30445/? E/Zygote: v2
05-02 21:11:10.238 30445-30445/? E/Zygote: accessInfo : 0
05-02 21:11:12.271 30445-30445/com.example.asus.autocare E/BoostFramework:
BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't
find class "com.qualcomm.qti.Performance" on path:
DexPathList[[],nativeLibraryDirectories=[/system/lib, /vendor/lib]]
05-02 21:11:30.904 30445-30445/com.example.asus.autocare E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.asus.autocare, PID: 30445
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asus.autocare/com.example.asus.autocare.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at com.example.asus.autocare.MapsActivity.setUpMap(MapsActivity.java:147)
at com.example.asus.autocare.MapsActivity.setUpMapIfNeeded(MapsActivity.java:140)
at com.example.asus.autocare.MapsActivity.onCreate(MapsActivity.java:64)
at android.app.Activity.performCreate(Activity.java:6955)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6776) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 
Try Moving these lines to onMapLoaded() instead.
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

Cannot get my current location using android maps activity and Fused Location API

I am trying to get my current location using GoogleApiClient and LocationListner. Below is my code which I got from Here.
But the problem is when I start this app in mobile. It is not giving me my current location. I also have checked in debug mode. Latitude and Longitude are not updating in variables. Please check this code and guide me where i am doing wrong or any other logical error. In tutorial developer make a boolean type function named checkLocationPermission(). But this function never used in application. Where should I call that function.
Thanks in advance
Here are my coding files
AndroidManifest.xml
`<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sufian.androidmaps">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<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">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>`
and My MapsActivity.java File is below
`
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener
{
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//initialize google play services
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 100;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
//toast here
}
return;
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority
(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient,
mLocationRequest,
(com.google.android.gms.location.
LocationListener) this);
}
}
#Override
public void onConnectionSuspended(int i){
}
The reason your not receiving update locations is because you check if you have location permissions which you don't have before building the Google ApiClient which triggers the location updates.
From Android 6 and higher these aren't granted automatically. But if you call checkLocationPermission() in OnCreate it should prompt the user to grant the permission as soon as you launch the activity

Categories

Resources