After call to ActivityCompat.requestPermissions, no dialog appears - android

I'm trying to implement location permissions in Android Marshmallow. I created a small test application, and everything is working perfectly. But when I copy that same code into my real application, the dialog "Allow [app name] to access this device's location?" never appears.
I can step through the debugger and see that ActivityCompat.requestPermissions() is called when it should be.
The only difference I can think of is that the real app has a lot more going on. The map activity is created from within a ScrollableTabActivity, like this:
this.addTab(getString(R.string.map), R.drawable.iconmap,
RadioStateDrawable.SHADE_GRAY,
RadioStateDrawable.SHADE_BLUE, new Intent(this, MapsActivity.class));
Do I need to think about threads, or anything like that? Or creating the activity in a different way?
Here's the full source code to the sample activity (where everything works):
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap map;
private Button gpsButton;
private static String[] LOCATION_PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION};
private static int ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE = 1;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
gpsButton = (Button) findViewById(R.id.GPS);
gpsButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
requestLocationPermissions();
}
});
}
private void requestLocationPermissions()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
new AlertDialog.Builder(MapsActivity.this)
.setMessage("Without access to your location, the app's location function cannot be used. Will you allow this access?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
ActivityCompat.requestPermissions(MapsActivity.this,
LOCATION_PERMISSIONS, ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE);
}
}).setNegativeButton(R.string.no, null).show();
}
else
{
ActivityCompat.requestPermissions(this, LOCATION_PERMISSIONS, ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE);
}
}
else
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults)
{
if (requestCode == ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE)
{
if (verifyPermissions(grantResults))
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else
{
new AlertDialog.Builder(MapsActivity.this)
.setMessage("Without access to your location, the app's location function cannot be used.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
}
}).show();
}
}
}
private void updateUserLocation(Location location)
{
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
locationManager.removeUpdates(this);
}
public static boolean verifyPermissions(int[] grantResults)
{
boolean verified = false;
for (int result : grantResults)
{
if (result == PackageManager.PERMISSION_GRANTED)
{
verified = true;
}
}
return verified;
}
#Override
public void onMapReady(GoogleMap googleMap)
{
map = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onLocationChanged(Location location)
{
updateUserLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
}

Related

I get: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission

I'm working with the map to my app and so I have here a weird error message that it says java.lang.SecurityException: "GPS" location provider requires ACCESS_FINE_LOCATION permission. every time I launch the app and crashes due to this error, though I already have a permission checker.
Here is my code:
public class FragmentHome extends Fragment implements OnMapReadyCallback {
/*
Set up's
*/
private static final String TAG = "FragmentHome";
/*
Pallete
*/
private MapView mapView;
private GoogleMap gMap;
private static final String MAP_VIEW_BUNDLE_KEY = "SOME_KEY";
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);
mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return view_fragmentInflate;
}
#Override
public void onMapReady(GoogleMap googleMap) {
getUserLocation();
}
private void getUserLocation() {
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
getContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
}
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
}
I really do not know where I went wrong from this line of code, to keep my app crashing and give me that error.
Update your code with bellow code may solve your problem
public class FragmentHome extends Fragment implements OnMapReadyCallback {
/*
Set up's
*/
private static final String TAG = "FragmentHome";
/*
Pallete
*/
private MapView mapView;
private GoogleMap gMap;
private static final String MAP_VIEW_BUNDLE_KEY = "AIzaSyDWL-JNHiCXvQefgFh1BdaAflJTveSrHJo";
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);
mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return view_fragmentInflate;
}
boolean isMapReady;
#Override
public void onMapReady(GoogleMap googleMap) {
isMapReady=true;
getUserLocation();
}
private void getUserLocation() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getContext(),Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(),Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
return;
}
}
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
}
Now override onRequestPermissionsResult() and check if result is granted and isMapReady flag true then call getUserLocation().
So the solution for this and base on the comments i forgot to put the else statement that if the permission is granted then execute the listener else request a permission.
Updated:
public class FragmentHome extends Fragment implements OnMapReadyCallback {
/*
Set up's
*/
private static final String TAG = "FragmentHome";
/*
Pallete
*/
private MapView mapView;
private GoogleMap gMap;
private static final String MAP_VIEW_BUNDLE_KEY = "AIzaSyDWL-JNHiCXvQefgFh1BdaAflJTveSrHJo";
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);
mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return view_fragmentInflate;
}
#Override
public void onMapReady(GoogleMap googleMap) {
checkGPSPermission();
getUserLocation();
}
private void checkGPSPermission() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
// show why is important
}
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
} else {
// granted
}
} else {
// granted
}
}
private void getUserLocation() {
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
getContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
}
}

how i can access current user location in fragments using API28?

i want to access current location in fragments , but i am using API 28 and android version 3.2.1. i try everything from internet follow tutorials but i cant access my current location , there is no error in my code but i don't know why i cant access it. when i run my program i just see google default map, no marker etc.
i want to access my location through network provider as well as gps provider if network provider is not available.
i also add permissions in manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
for a permission access i am using library from github and for lacation and map
implementation 'pub.devrel:easypermissions:2.0.0'
implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
please check my code and guide me how i can access current location my code is in below in my code there is also step counter code but ignore that one.
here is my code
public class HomeActivity extends Fragment implements SensorEventListener, OnMapReadyCallback {
SensorManager sensorManager;
TextView set_steps;
TextView set_calories;
TextView set_distance;
boolean running = false;
private static int steps;
private static int calories;
private static double distance;
private GoogleMap mMap;
LocationManager locationManager;
public static final int Request_User_Location_Code = 99;
GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private final int REQUEST_LOCATION_PERMISSION = 1;
Provider provider;
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_home, container, false);
requestLocationPermission();
stepsCounter();
locationTracker();
return view;
}
void stepsCounter() {
set_steps = (TextView) view.findViewById(R.id.set_steps);
set_calories = (TextView) view.findViewById(R.id.set_calories);
set_distance = (TextView) view.findViewById(R.id.set_distance);
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
sensorManager.registerListener((SensorEventListener) getActivity(), countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(getActivity(), "Sensor not Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPause() {
super.onPause();
running = false;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (running) {
steps = (int) event.values[0];
set_steps.setText(steps + "");
caloriesCounter();
distanceCover();
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
void caloriesCounter() {
calories = steps / 20;
set_calories.setText(calories + "");
}
void distanceCover() {
distance = (double) steps * 0.76;
String distanceText = Double.toString(distance);
set_distance.setText(distanceText);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
void locationTracker() {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if ((ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng= new LatLng(latitude,longitude);
Geocoder geocoder=new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude,longitude,1);
String str = addressList.get(0).getLocality()+",";
str+= addressList.get(0).getCountryName();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
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) {
}
});
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng= new LatLng(latitude,longitude);
Geocoder geocoder=new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude,longitude,1);
String str = addressList.get(0).getLocality()+",";
str+= addressList.get(0).getCountryName();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
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) {
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
#AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(getActivity(), perms)) {
// Toast.makeText(getActivity(), "Permission already granted", Toast.LENGTH_SHORT).show();
}
else {
EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
}
}
}
but remember i am using ApI 28

onLocationChanged not being called

I'm having a problem with my android app where I cannot retrieve the devices current location. From debugging the app it appears that onLocationChange within my LocationListener is not firing.
I have set up requestLocationUpdates to work with my LocationListener, along with an output to the Log within onLocationChange but I am receiving nothing.
I've also noticed that there's no GPS icon appearing in the top bar of the phone when I'm using the app but if I switch over to the Google Maps app, the icon appears instantly...I'm struggling with this at this point so any help would really be appreciated. Thanks.
MapFragment.java:
public class MapFragment extends Fragment implements OnMapReadyCallback {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private OnFragmentInteractionListener mListener;
private SupportMapFragment mapFragment;
private GoogleMap googleMap;
LocationManager locationManager;
public MapFragment() {
// Required empty public constructor
}
public static MapFragment newInstance() {
MapFragment fragment = new MapFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_map, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.onCreate(savedInstanceState);
mapFragment.onResume();
mapFragment.getMapAsync(this);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
checkLocationPermission();
}
#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) {
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
}
} else {
// functionality that depends on this permission.
}
return;
}
}
}
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
//your code here
Log.v("LOCATION UPDATE", "IN ON LOCATION CHANGE, lat=" + location.getLatitude() + ", lon=" + location.getLongitude());
/*
LatLng userPosition = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(userPosition)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin_fill))
.title("Test Pin"));*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
//dialog to ask for permission
new AlertDialog.Builder(getActivity())
.setTitle("Permission")
.setMessage("Need permission")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
}
else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
}
return false;
} else {
return true;
}
}
}
Not sure if relevant but
fragment_map.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapFragment" />
Are you sure locationManager.requestLocationUpdates() is executing? Based on this code, if ACCESS_FINE_LOCATION is already granted upon startup, checkLocationPermission() will return true, and nothing ever calls requestLocationUpdates().

How to use locationListener in android fragment

I want to use locationListener in my android fragment. But I am getting an error. My code is in below.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
};
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 1, locationListener);
}
else {
}
}
I am getting this error.
Can't resolve method requestLocationUpdates
Implement all the methods of LocationListener
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setText(R.string.hello_blank_fragment);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if (new Utility().checkAndGrantPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION, 101, "your custom message"))
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 1, locationListener);
}
return textView;
}
Outside from onCreate
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Todo your code
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
//Todo your code
}
#Override
public void onProviderEnabled(String provider) {
//Todo your code
}
#Override
public void onProviderDisabled(String provider) {
//Todo your code
}
};
And the checkAndGrantPermission method is
public boolean checkAndGrantPermission(final Context context, final String permissionString, final int requestCode, String permissoinTypeMessage)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, permissionString) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, permissionString)) {
// your custom dialog screen when user deny permission
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{permissionString}, requestCode);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
In Activity override onRequestPermissionsResult
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 101) {
yourFragmentInstance.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
}
In Your Framgent override onRequestPermissionsResult
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 101) {
if (requestCode == AppConstants.runtimePermissionCode) {
if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 1, locationListener);
}
}
}
}
Got your issue.
You have used Location listener from
com.google.android.gms.location.LocationListener;
You have to import LocationListener from
android.location.Location;
Try this one:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 1, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
Hope it helps:)
Create this class:
public class GetCurrentLocation implements
ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
private static final String TAG = "location-updates-sample";
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 0;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
private final String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
private final String LOCATION_KEY = "location-key";
private final String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Context mContext;
private getLocation mGetCurrentLocation;
public GetCurrentLocation(Context context) {
mContext = context;
buildGoogleApiClient();
}
private synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
public interface getLocation{
public void onLocationChanged(Location location);
}
public void startGettingLocation(getLocation location) {
mGetCurrentLocation = location;
connect();
}
public void stopGettingLocation() {
stopLocationUpdates();
disconnect();
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void startLocationUpdates() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
private void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
private void connect() {
mGoogleApiClient.connect();
}
private void disconnect() {
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
startLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
mGetCurrentLocation.onLocationChanged(location);
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
}
In your fragment class:
private GetCurrentLocation mListen;
mListen = new GetCurrentLocation(this);
mListen.startGettingLocation(new GetCurrentLocation.getLocation() {
#Override
public void onLocationChanged(Location location) {
// Here is my working with location object
}
});
make sure you have added latest googleplayservice library in your gradle file.

Android - Google Maps - LocationListener - adding marker onLocationChanged makes app crash

I want a marker to show my current location. All permissions needed are added. When I comment out mMap.addMarker and mMap.moveCamera the app is working and Googlemaps is shown. If I let one of those two in my code the app crashes before the map even opens.
I've tried with removing the marker if it isn't null but this doesn't solve the problem.
Do you guys have any idea how I can get the app working?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private List<LatLng> fountain = null;
private LocationManager locationManager;
private double posLat;
private double posLng;
private LatLng position;
private Marker mPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
startGPS();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(48.16786112327462, 16.383984438313828);
mPosition = mMap.addMarker(new MarkerOptions().position(sydney).title("Your Position").icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
//--------------------------------------------GPS Listener---------------------------------------
public void startGPS() {
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) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 5);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this);
onLocationChanged(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 5: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
getDialog2("Keine Erlaubnis für GPS").show();
}
}
}
}
#Override
public void onLocationChanged(Location location) {
posLat = location.getLatitude();
posLng = location.getLongitude();
position = new LatLng(posLat, posLng);
if (mPosition != null) {
mPosition.remove();
}
mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//----------------------------Helper Methods-----------------------------------------------
public Dialog getDialog2(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
return builder.create();
}
public Dialog getDialog(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
Okay, I already solved the problem. So I post the solution here.
I have implemented on the MapsActivity the LocationListener interface and for some reason it doesn't work this way. I can retrieve the geocoordinates but as soon as I want to move the camera or add a marker it the app crashes as it gets opened.
I don't know why, but instead of:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this)
I undo the implementation of the LocationListener and just create a new one at the position of ,,this":
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
posLat = location.getLatitude();
posLng = location.getLongitude();
position = new LatLng(posLat, posLng);
if (mPosition != null) {
mPosition.remove();
}
mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
);
and this way it works without problem.

Categories

Resources