In my app I need for location of users.
I realize that I must ask for permission, but how I can do this on Android 5.1.1 where user cannot change permission. I wrote the code that is everywhere but without result.
How must I proceed?
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.Manifest;
//import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.*;
//import com.google.android.gms.maps.model.LatLng;
//import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
//import com.google.android.gms.common.api.*;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
, GoogleApiClient.ConnectionCallbacks
//, OnConnectionFailedListener
{
private GoogleMap mMap;
// public GoogleApiClient.Builder mGoogleApiClient = new GoogleApiClient.Builder(this);
private GoogleApiClient mGoogleApiClient;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public double latitude;
public double longitude;
#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);
//mMainActivity.onConnected(bBundle);
Log.d("OnCreate", "enter 1");
mGoogleApiClient = new GoogleApiClient.Builder(this)
//.enableAutoManage(this /* FragmentActivity */,
// this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
// .addApi(Places.GEO_DATA_API)
//.addApi(Places.PLACE_DETECTION_API)
.build()
;
mGoogleApiClient.connect();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("OnCreate", "enter in if1 ");
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
Log.d("OnCreate", "enter in if2 ");
} else {
Log.d("OnCreate", "enter in else2 Request permission ");
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
//Request location updates: Popytka
//locationManager.requestLocationUpdates(provider, 400, 1, this);
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d("OnCreate", "enter mLastLocation " + String.valueOf(mLastLocation));
if (mLastLocation != null) {
Log.d("OnCreate", "enter2");
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Log.d("OnCreate longitude", String.valueOf(longitude));
}
}
}
//public MainActivity mMainActivity = new MainActivity();
Bundle bBundle;
#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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
//locationManager.requestLocationUpdates(provider, 400, 1, this);
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d("OnCreate", "enter mLastLocation " + String.valueOf(mLastLocation));
if (mLastLocation != null) {
Log.d("OnCreate","enter20");
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Log.d("OnCreate longitude-0", String.valueOf(longitude));
}
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
//System.out.println("onMapReady in");
mMap = googleMap;
//latitude = -34;
//longitude = 151;
float zoom = 5;
double laRe = latitude, loRe = longitude+1;
// Add a marker in Sydney and move the camera
LatLng user = new LatLng(latitude, longitude), rest = new LatLng(laRe, loRe);
//LatLng rest = new LatLng(laRe, loRe);
mMap.addMarker(new MarkerOptions().position(user).title("Marker in USER"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(user, zoom));
mMap.addCircle(new CircleOptions()
.center(user)
.radius(200000)
.strokeColor(0)
.fillColor(0x4000ff00));
GroundOverlayOptions restPos = new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher))
.position(new LatLng(laRe, loRe), 200000f);
mMap.addGroundOverlay(restPos);
}
#Override
public void onConnected (Bundle bBundle){
}
protected void onStart() {
//mGoogleApiClient.connect();
super.onStart();
//mGoogleApiClient.ConnectionCallbacks; //(this);
}
protected void onStop() {
// mGoogleApiClient.disconnect();
super.onStop();
}
public void onConnectionSuspended(int i) {
}
//#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
<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" >
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<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>
SDK 25
Runtime permission is required for Android 6.0+ but if you need here's the easiest code for requesting runtime permissions.
String [] permissions=new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION
};
List<String> listPermissionsNeeded = new ArrayList<>();
for (String permission:permissions) {
if (ContextCompat.checkSelfPermission(this,permission )!= PackageManager.PERMISSION_GRANTED){
listPermissionsNeeded.add(permission);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 1);
}
UPDATE
Try this ->
First, create a LocationRequest object:
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
Then, make sure the user has granted permission to use location. If so, get the location from requestLocationUpdates as follows:
void getLocation() {
Location location = null;
if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
/*TODO!! INSERT CODE TO PROMPT USER TO GIVE PERMISSION*/
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
mLastLocation = location;
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
Be sure to remove the updates if you only need one location without constant monitoring. This way, you will never get a null Location.
Related
I am making an app to show user location on google map by put a marker in his/her current location when i run the app it only gives me the view of the map without doing any thing else , i searched too many but i do not find any thing to help me can anyone guide me through this.
thanks in advance.
MapsActivity.java
package com.example.android.getlocationtrial;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager manager;
private LocationListener locationListener;
#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);
//get the location service
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
//request the location update thru location manager
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,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getSubLocality()+":";
result += addresses.get(0).getLocality()+":";
result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title(result));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, locationListener);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// 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));
*/
}
#Override
protected void onPause() {
super.onPause();
manager.removeUpdates(locationListener);
Log.i("onPause...","paused");
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.getlocationtrial">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_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:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<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>
In order to show the current location marker you just call setMyLocationEnabled on your map object and pass true as its parameter.
Check the following code snippit:
private static final int LOCATION_REQUEST = 50;
private String[] LOCATION_PERMS = {android.Manifest.permission.ACCESS_FINE_LOCATION };
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Asking for location permission to request the last user location
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
LOCATION_PERMS,
LOCATION_REQUEST);
} else {
ActivityCompat.requestPermissions(this,
LOCATION_PERMS,
LOCATION_REQUEST);
}
} else {
//This will show the current user location marker
mMap.setMyLocationEnabled(true);
//Getting location updates and focus the camera with the latest location
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// ...
userCurrentLocation = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cp = CameraPosition.builder().target(userCurrentLocation).zoom(25).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp), 500, null);
}
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUEST: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay!
onMapReady(mMap);
} else {
// permission denied,
// Ask again for the permission
Toast.makeText(this, R.string.location_permission_required_message, Toast.LENGTH_SHORT).show();
finish();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
When I run it the output is showing that "permission denied", thats in my else part.
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
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.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
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);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions, #NonNull int[] 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 denied
{
Toast.makeText(this,"Permission denied",
Toast.LENGTH_LONG).show();
}
return;
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the
camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be
prompted to install
* it inside the SupportMapFragment. This method will only be triggered once
the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if
(ContextCompat.
checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATI
ON) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
#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
(Activity
Compat.shouldShowRequestPermissionRationale(this,Manifest.permission.A
CCESS_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 onLocationChanged(Location location) {
lastLocation = location;
if(currentLocationMarker != null) {
currentLocationMarker.remove();
}
LatLng latLng = new
LatLng(location.getLongitude(),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 onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
and my android manifest file is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kerthi.map2">
<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: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>
I think there is a mistake in the if, I am not sure. Please kindly help me.
Is there anything else which I should add?
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.oit.test.mygoogle">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<permission
android:name="com.sa.com.oit.test.mygoogle.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<application
android:allowBackup="true"
android:icon="#mipmap/shiv"
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">
</activity>
<activity
android:name=".MapLocationActivity"
android:label="#string/title_activity_maps">
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity
package com.oit.test.mygoogle;
import android.*;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
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.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapLocationActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationManager locationManager;
public static final int REQUEST_LOCATION = 100;
double mLatitude;
double mLongitude;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkLocationPermission();
}
else
{
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
showGPSDisabledAlertToUser();
}
}
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
private void showGPSDisabledAlertToUser()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Settings", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
mapFrag.getMapAsync(MapLocationActivity.this);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public void onPause()
{
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
else
{
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_LOCATION);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
} else {
mGoogleMap.setMyLocationEnabled(true);
//Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
LatLng coordinate = new LatLng(mLatitude, mLongitude);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 10);
mGoogleMap.animateCamera(yourLocation);
return true;
}
return false;
}
});
}
protected synchronized void buildGoogleApiClient()
{
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle)
{
mLocationRequest = new LocationRequest();
/* mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);*/
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
/* if (mCurrLocationMarker != null)
{
mCurrLocationMarker.remove();
}*/
LatLng opt = new LatLng(22.57, 88.43);
mGoogleMap.addMarker(new MarkerOptions().position(opt).title("Shivi").icon(BitmapDescriptorFactory.fromResource(R.mipmap.marker)));
LatLng opt2 = new LatLng(22.50, 88.53);
mGoogleMap.addMarker(new MarkerOptions().position(opt2).title("Sarthak").icon(BitmapDescriptorFactory.fromResource(R.mipmap.marker)));
LatLng opt3 = new LatLng(22.67, 88.35);
mGoogleMap.addMarker(new MarkerOptions().position(opt3).title("Mitra").icon(BitmapDescriptorFactory.fromResource(R.mipmap.marker)));
LatLng opt4 = new LatLng(22.47, 88.43);
mGoogleMap.addMarker(new MarkerOptions().position(opt4).title("Boss").icon(BitmapDescriptorFactory.fromResource(R.mipmap.marker)));
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
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 = mGoogleMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to location user
.zoom(10) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
/* //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 = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));*/
//stop location updates
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
else
{
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
}
else
{
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
showGPSDisabledAlertToUser();
}
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, yay! Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
showGPSDisabledAlertToUser();
}
if (mGoogleApiClient == null)
{
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
}
else
{
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
I am trying to ask the user permission to access their location. This is my MainActivity but permission is not being asked when I run the app. I have entered the code for permissions at the end of the activity. What am I doing wrong?
package com.example.googlemapsadding;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener
{
private GoogleMap mMap;
private final String LOG_TAG = "LaurenceTestApp";
private TextView txtOutput;
private TextView latitude;
private TextView longitude;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
Marker curPosMarker;
#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);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
txtOutput = (TextView) findViewById(R.id.txtOutput);
latitude = (TextView) findViewById(R.id.latitude);
longitude = (TextView) findViewById(R.id.longitude);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app
*/
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
/* Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(10,19);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
*/
}
#Override
public void onConnected(#Nullable Bundle bundle)
{
mLocationRequest = LocationRequest.create(); // Another way to write a new object
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(2 * 1000); // Always write in milliseconds
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i)
{
Log.i(LOG_TAG, "GoogleApiClient connection has been suspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
Log.i(LOG_TAG, "GoogleApiClient connection has failed");
}
#Override
public void onLocationChanged(Location location)
{
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
Log.i(LOG_TAG, location.toString());
double tempLat = location.getLatitude();
double tempLong = location.getLongitude();
// Make a marker
LatLng latlng = new LatLng(tempLat,tempLong);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
/*
MarkerOptions markerOptions = new MarkerOptions(); // MarkerOptions object to hold marker attributes
markerOptions.position(latlng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
markerOptions.title("Current Position");
curPosMarker = mMap.addMarker(markerOptions); // Add marker with markerOptions options
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
if (curPosMarker != null) // Keep only one marker for an object and delete past ones
{
mMap.clear();
}
curPosMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
*/
}
#Override
protected void onStart()
{
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop()
{
mGoogleApiClient.disconnect();
super.onStop();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
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)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//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. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//if (mGoogleApiClient == null) {
// buildGoogleApiClient();
//}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}
I think you should request GRANTED with ALL LOCATION PERMISSION
String mPerms[] = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
...
if (checkSelfPermission(mPerms[0]) == PackageManager.PERMISSION_DENIED
|| checkSelfPermission(mPerms[1]) == PackageManager.PERMISSION_DENIED) {
requestPermissions(mPerms, CODE_PERMISSION_LOCATION);
} else {
// TODO Location checker
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(resultCallback);
}
Try Google Utilities library to get location easily with permission..
locationHandler = new LocationHandler(this)
.setLocationListener(new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Get the best known location
}
}).start();
For more details about location handler, read out wiki...
check the target version in your build.gradle file, it should be 23 or higher.
Solved. I completely erased my permission code and followed this tutorial from scratch - https://www.youtube.com/watch?v=z2JaVke71RY. Worked perfectly.
I want to add a geofence on the current location of the user when the user clicks on the ad geofence button.however,after using fused api client it states that its not connected yet.here is my code-
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
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.Geofence;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap googleMap; // Might be null if Google Play services APK is not available.
public SQLiteDatabase db;
ArrayList<Geofence> mGeofences;
public double latitude = 77.80;
public double longitude = 55.76;
Double valueindex = 0.0;
private int request = 0;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
/**
* Geofence Coordinates
*/
ArrayList<LatLng> mGeofenceCoordinates;
/**
* Geofence Store
*/
private GeofenceStore mGeofenceStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGeofences = new ArrayList<Geofence>();
mGeofenceCoordinates = new ArrayList<LatLng>();
db = openOrCreateDatabase("CoordsDB", Context.MODE_PRIVATE, null);
// db.execSQL("CREATE TABLE IF NOT EXISTS Coordinates(number DOUBLE,latitude DOUBLE,longitude DOUBLE);");
// db.execSQL("INSERT INTO Coordinates VALUES('Fixed', 28.61,77.20)");
setContentView(R.layout.activity_maps);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
/**
* SupportMapFragment belongs to the v4 support library, contrary to the default MagFragment that is a native component in Android.
SupportMapFragment will support more Android versions, but it is also an additional library you have to add in your project,
so I think it really depends on the Android versions you are targeting:
• On recent versions, the default components should be enough
• On older versions you will need to install the v4 support library and maybe others
*
*/
googleMap = supportMapFragment.getMap();
Log.i("My activity", "maps=" + googleMap);
googleMap.setMyLocationEnabled(true);
/**
* setMyLocationEnabled(true/false) shows the true location when the GPS is switched on from the device. It is an inbuilt feature of the googlemaps .
*/
LocationManager locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("My activity", "gps is" + isGPSEnabled);
// getting network status
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.i("My activity", "network is" + isNetworkEnabled);
Criteria crta = new Criteria();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
crta.setAccuracy(Criteria.ACCURACY_FINE);
} else {
crta.setAccuracy(Criteria.ACCURACY_MEDIUM);
}
/**
* we have used .setAccuracy as fine for higher SDks than gingerbread .Gingerbread is used as a reference because in apks lower
* than gingerbread there is very poor geofencing, with gingerbread google made it a lot easier for locationservices to be used for devleopers.
* it had improved set of tools for Location Services, which included geofencing and substantially improved location discovery.
*/
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
/**
* It request Location updates after every 5 sec or if the user traveled 10m
*/
Log.i("My activity", "manager is " + locationManager);
Log.i("My activity", "provider is " + provider);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
MapsActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
}
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
Log.i("Api is",""+mGoogleApiClient);
}
mLocationRequest = new LocationRequest();
// We want a location update every 10 seconds.
mLocationRequest.setInterval(10000);
// We want the location to be as accurate as possible.
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Location location = locationManager.getLastKnownLocation(provider);
Location location = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
startLocationUpdates();
Log.i("Location is", location + "");
if (location != null) {
onLocationChanged(location);
}
/**
* the Permission is requested after every sec or at a distance of 0 metres by the user.
*/
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 100: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Thanks for the permission", Toast.LENGTH_LONG).show();
// permission was granted, yay! do the
// calendar task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "You did not allow to access your current location", Toast.LENGTH_LONG).show();
}
}
// other 'switch' lines to check for other
// permissions this app might request
}
}
#Override
public void onLocationChanged(Location location) {
CameraPosition INIT =
new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude()))
.zoom(17.5F)
.bearing(300F) // orientation
.tilt(50F) // viewing angle
.build();
// use GooggleMap mMap to move camera into position
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(INIT));
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
public void Add(View view) {
if (request <= 3) {
mGeofenceCoordinates.add(new LatLng(latitude, longitude));
Log.i("The id is", "" + valueindex);
mGeofences.add(new Geofence.Builder()
// The coordinates of the center of the geofence and the radius in meters.
.setRequestId("" + valueindex)
.setCircularRegion(latitude, longitude, 30)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
// Required when we use the transition type of GEOFENCE_TRANSITION_DWELL
.setLoiteringDelay(50000)
.setTransitionTypes(
Geofence.GEOFENCE_TRANSITION_ENTER
| Geofence.GEOFENCE_TRANSITION_DWELL
| Geofence.GEOFENCE_TRANSITION_EXIT).build());
mGeofenceStore = new GeofenceStore(this, mGeofences);
valueindex++;
request++;
// Cursor c = db.rawQuery("SELECT * FROM Coordinates WHERE Id='"+valueindex+"'", null);
googleMap.addMarker(new MarkerOptions().snippet("Radius:30m").draggable(false).title(valueindex + "").position(new LatLng(latitude, longitude)));
} else {
Toast.makeText(this, "Maximum limit exceeded", Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnected(Bundle bundle) {
Location mlastlocation;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
MapsActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
}
mlastlocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
startLocationUpdates();
if (mlastlocation != null) {
Log.i("the last location:", "" + mlastlocation);
Toast.makeText(this, "Get last location first asshole!", Toast.LENGTH_LONG).show();
}
}
protected void startLocationUpdates() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
MapsActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
LocationRequest mLocationRequest = new LocationRequest();
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i("connection","suspended");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i("Connection","Failed");
}
}
Here is my error-
java.lang.RuntimeException: Unable to start activity ComponentInfo{saksham.geofencing/saksham.geofencing.MapsActivity}: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
at com.google.android.gms.common.api.internal.zzh.zzb(Unknown Source)
at com.google.android.gms.common.api.internal.zzl.zzb(Unknown Source)
at com.google.android.gms.common.api.internal.zzj.zzb(Unknown Source)
at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source)
at saksham.geofencing.MapsActivity.startLocationUpdates(MapsActivity.java:276)
at saksham.geofencing.MapsActivity.onCreate(MapsActivity.java:139)
at android.app.Activity.performCreate(Activity.java:6245)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
and my manifest file-
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="saksham.geofencing" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<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:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.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>
<receiver android:name="com.aol.android.geofence.GeofenceReceiver"
android:exported="false">
<intent-filter >
<action android:name="com.aol.android.geofence.ACTION_RECEIVE_GEOFENCE"/>
</intent-filter>
</receiver>
</manifest>
Please help,i am newbie to android and i have been stuck at it for many days now even after searching countless blogs
In your onCreate method, you correctly configure the Google API Client and call onConnect:
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
Log.i("Api is",""+mGoogleApiClient);
}
However, several lines below this (still within the onCreate lifecycle method), you have the following code:
Location location = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
startLocationUpdates();
Log.i("Location is", location + "");
if (location != null) {
onLocationChanged(location);
}
My guess is that the first line of this section is causing the error - you are trying to retrieve a location but the Google API Client is still not connected at this point. Since you already have analogous code inside your onConnected callback, you should be able to just remove the second block of code I quoted above from your onCreate method to fix the issue.
I got current Location in Below 23 devices but getting (0.0,0.0) latitude and Longitude in 23 emulator device.
EDIT
Currently I am using Fused Location Provider for get Current Location
public class ContactUsFragment extends Fragment implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("TAG", "OnCreate Called");
locationManager = (LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE);
buildGoogleApiClient();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_contact_us, container, false);
Log.i("TAG", "OnCreateView Called");
setComponants(view); // **** Method For Set Componants Of Layout
This is Map Image on click of it I want to get current Location and pass it to Native Google Map app of device for navigate to target Location
mapImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("TAG", "On ImageView Click");
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, getActivity().getApplicationContext(), getActivity())) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
navigateToGoogleMap();
} else {
showSettingsAlert();
}
} else {
requestPermission(Manifest.permission.ACCESS_FINE_LOCATION, PERMISSION_REQUEST_CODE, getActivity().getApplicationContext(), getActivity());
}
} else {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
navigateToGoogleMap();
} else {
showSettingsAlert();
}
}
}
});
return view;
}
Below is code for get Current Location
private synchronized void buildGoogleApiClient() {
Log.i("TAG", "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity().getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
//**************************
builder.setAlwaysShow(true); //this is the key ingredient
//**************************
}
#Override
public void onConnected(Bundle bundle) {
Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// Note that this can be NULL if last location isn't already known.
if (mCurrentLocation != null) {
// Print current location if not null
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
currentlatitude = mCurrentLocation.getLatitude();
currentlongitude = mCurrentLocation.getLongitude();
}
// Begin polling for new location updates.
startLocationUpdates();
}
private void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
private void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onConnectionSuspended(int i) {
if (i == CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(getActivity().getApplicationContext(), "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
} else if (i == CAUSE_NETWORK_LOST) {
Toast.makeText(getActivity().getApplicationContext(), "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
}
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
currentlatitude = location.getLatitude();
currentlongitude = location.getLongitude();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
*This code is Working Properly when I use in below API23 devices but when I try on marshmallow Device it give current Location 0.0,0.0 *
Below is my Manifest file
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-library android:name="com.google.android.maps" />
<!-- Required OpenGL ES 2.0. for Maps V2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/Theme.AppCompat.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".HomeMainActivity"
android:label="#string/app_name"
android:windowSoftInputMode="adjustPan"
android:screenOrientation="portrait"
>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#layout/searchable" />
</activity>
<activity
android:name=".HomeActivity"
android:screenOrientation="portrait" />
<activity
android:name=".DoctorsDetailsActivity"
android:screenOrientation="portrait" />
<activity android:name=".ServiceActivity" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Use below code. Hope this is useful.
Make sure you run this code into real device only.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
MainActivity.java
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener
{
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkLocationPermission();
}
else
{
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
showGPSDisabledAlertToUser();
}
}
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
private void showGPSDisabledAlertToUser()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Settings", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
mapFrag.getMapAsync(MainActivity.this);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public void onPause()
{
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
else
{
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient()
{
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle)
{
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
#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 = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
else
{
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
}
else
{
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
showGPSDisabledAlertToUser();
}
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, yay! Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
showGPSDisabledAlertToUser();
}
if (mGoogleApiClient == null)
{
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
}
else
{
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sneha.mymapdemo">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR API KEY"/>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
I got exact problem after some debugging and searching
GoogleAPIclient onConnected() not called so it called onConnectionFailed() method
In that Method I found error code it was 2 it mean REQUIRED PLAY SERVICE UPDATE
so I change play service in gradle file same as Device Playservice version so I get Current Location
I post Some code Here:
private synchronized void buildGoogleApiClient() {
Log.i("TAG", "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity().getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();}
private void createLocationRequest() {
Log.i("TAG", "CreateLocationRequest");
mLocationRequest = new LocationRequest();
long UPDATE_INTERVAL = 10 * 1000;
mLocationRequest.setInterval(UPDATE_INTERVAL);
long FASTEST_INTERVAL = 10000;
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
//**************************
builder.setAlwaysShow(true); //this is the key ingredient
//**************************
}
private void startLocationUpdates() {
Log.i("TAG", "StartLocationUpdates");
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
private void stopLocationUpdates() {
Log.i("TAG", "StopLocationUpdates");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i("TAG", "onConnectionSuspended");
if (i == CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(getActivity().getApplicationContext(), "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
} else if (i == CAUSE_NETWORK_LOST) {
Toast.makeText(getActivity().getApplicationContext(), "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
}
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
Log.i("TAG", "OnLocationChanged");
Log.i("TAG", "Current Location==>" + location);
currentlatitude = location.getLatitude();
currentlongitude = location.getLongitude();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(getActivity(), connectionResult.RESOLUTION_REQUIRED);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.e("TAG", "Location services connection failed with code==>" + connectionResult.getErrorCode());
Log.e("TAG", "Location services connection failed Because of==> " + connectionResult.getErrorMessage());
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mGoogleApiClient != null)
mGoogleApiClient.disconnect();
}
#Override
public void onConnected(Bundle bundle) {
Location mCurrentLocation;
Log.i("TAG", "OnConnected");
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// Note that this can be NULL if last location isn't already known.
if (mCurrentLocation != null) {
// Print current location if not null
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
currentlatitude = mCurrentLocation.getLatitude();
currentlongitude = mCurrentLocation.getLongitude();
} else {
startLocationUpdates();
}
}
} else {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// Note that this can be NULL if last location isn't already known.
if (mCurrentLocation != null) {
// Print current location if not null
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
currentlatitude = mCurrentLocation.getLatitude();
currentlongitude = mCurrentLocation.getLongitude();
}
// Begin polling for new location updates.
startLocationUpdates();
}
}
For more Refer Official Docs https://developers.google.com/android/guides/setup
It maybe help you to known that.
I found that the Network provider not working in some android devices When you disable GPS because they're prevent access location data if GPS not enabled.
I've tried that on many devices
1. lenove k6 note (screen shot1 , screen shot2)
2. Xiomai mi 9t screen shot1
3. Google Pixel 1 & Pixel 2
so some devices need GPS enabled to access location from LocationManager.NETWORK_PROVIDER and you can't get location data without enable GPS