I could write code that get user's location and that works fine in API < 23. But in API 23 and above, my code return nothing in Log.
More Details:
I enable manually device's GPS.
In the first run the app request permission and no log returns.
In the next running the app return my prepared Toast (Check your provider).
this is my wrote code:
public class MainActivity extends AppCompatActivity implements LocationListener {
private static final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 124;
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 123;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_FINE_LOCATION);
}
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_COARSE_LOCATION);
}
}
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;
}
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), false);
Location location = locationManager.getLastKnownLocation(provider);
if (location == null) {
Toast.makeText(this, "Check your provider", Toast.LENGTH_SHORT).show();
} else {
Log.i("New Location", "lat: " + location.getLatitude());
Log.i("New Location", "lng: " + location.getLongitude());
}
}
#Override
public void onLocationChanged(Location location) {
Log.i("Location", "lat: " + location.getLatitude());
Log.i("Location", "lng: " + location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
In Android API 23+ there is a new way to handle permissions considered as "dangerous", that´s the case of android.permission.ACCESS_FINE_LOCATION and android.permission.ACCESS_COARSE_LOCATION among others.
You don´t need to handle android.permission.ACCESS_COARSE_LOCATION if you are already using the android.permission.ACCESS_FINE_LOCATION.
Please take a look at this link from the official documentation which shows you how to handle permissions at runtime in Android API 23+.
https://developer.android.com/training/permissions/requesting.html
This one might also help you.
https://developer.android.com/guide/topics/location/strategies.html
How to check for permissions:
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_FINE_LOCATION);
How to request for permissions:
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
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.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
// MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
Note that even if you request for permissions at runtime you will still have to keep the permission entry in the android manifest like this:
<manifest ... >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...
<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
...
</manifest>
After checking and granting permissions you should review the link with the location strategies above, there you can find the details of what you are missing.
Basically you are not registering the listener to receive the location updates. After adding this line at the end of the onCreate() method you should start seeing the location updates in your log.
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Related
I have used the following code and the dialogue that asks for permission shows as expected. But when I click "allow" it doesn't do anything. The log message doesn't appear as if the permission wasn't granted so I went to my parameters to verify if location is "on" and it was "off". Wasn't it supposed to be on because I granted the app access to my location ?
If I manually turn it "on" and then run the app again, once it asks for my permission, it works and shows the log message but isn't the whole point of asking for permissions (via dialogue) to turn on location (when it's off) if the user clicks "allow" ?
Am I doing something wrong ? I should mention that I'm running the app on api23
is is the code in my Oncreate:
mApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mApiClient.connect();
// 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
and this is my OnConnected method:
public void onConnected(#Nullable Bundle bundle) {
//start the service
//checking and asking for permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_ACCESS_FINE_LOCATION);
}
// 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;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient, mLocationRequest, this);
} else {
//If everything went fine lets get latitude and longitude
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.v("currentLatitude",currentLatitude + " WORKS " + currentLongitude + "");
}
}
try this code:
private LocationCoord gps = null;
private static final int PERMISSION_REQUEST_CODE = 1;
In OnCreate():
//GPS Manage
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Allow ImHere to access this device's location?");
dialog.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton("Deny", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
gps = new LocationCoord(this);
#Override
protected void onStart() {
super.onStart();
// permission android 6.0
if (!checkPermission()) {
requestPermission();
}
}
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED) return true;
else return false;
}
private void requestPermission(){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
You will need this permissions on the Manifest.xml:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<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.ACCESS_WIFI_STATE" />
You can get LoocationCord.java here: https://github.com/toomyy94/ImHere-Chatbot/blob/master/app/src/main/java/pt/ua/tomasr/imhere/modules/LocationCoord.java
you might have to add a dependency in your build.gradle:
compile 'com.google.android.gms:play-services-location:10.0.1
I am trying to get location of the virtual device AVD the problem here that the location return by null , i have added the permission to the app and still failed to get location
public class MainActivity extends AppCompatActivity implements LocationListener {
LocationManager locationManager;
String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
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.
Log.i("Location Info","Permission Denied");
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
Log.i("Location Info","Location Achieved ");
} else {
Log.i("Location Info", "Location Failed");
}
}
#Override
protected void onResume() {
super.onResume();
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;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
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;
}
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
Double longitude = location.getLongitude();
Double latitude = location.getLatitude();
Log.i("location Info Lat",longitude.toString());
Log.i("Location Info long",longitude.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
the result is all the time log info :Location Failed , what is the solution in this case
Location is null on emulator because it doesen't know your last sent location (fresh start or something else). You need to send your coordinates to emulator. Works better when you test on a real device.
Edit:
Enter coordinates like in this image.
The problem here was as mentioned by #Florescu it starts from unknown state when i give the emulator the dimension for the first time , find out the emulator understand this as a movement but when i run it again it gives me the correct behavior
I'm developing an app and using following code to fetch current coordinates of the user (from this library):
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(getBaseContext());
locationProvider.getLastKnownLocation().subscribe(new Action1<Location>() {
#Override
public void call(Location location) {
currentLatDouble = location.getLatitude();
currentLngDouble = location.getLongitude();
Toast.makeText(getBaseContext(), "User's location retrieved using library for android M in btnRetryGpsEvents()", Toast.LENGTH_SHORT).show();
}
});
The problem is that this code sometimes don't even gets executed even after all the conditions are true. See the code below:
if (currentLatDouble != null || currentLngDouble != null) {
retrieveHWrapper();
progressBarLoadingRequests.setVisibility(View.VISIBLE);
btnRetryGps.setVisibility(View.INVISIBLE);
gps_off.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(), "Loading hrequests...", Toast.LENGTH_LONG).show();
} else {
gps_off.setVisibility(View.VISIBLE);
progressBarLoadingRequests.setVisibility(View.INVISIBLE);
btnRetryGps.setVisibility(View.VISIBLE);
btnRetryGps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnRetryGpsEvents();
int hasWriteContactsPermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) & ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) & ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) & ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_SETTINGS);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_SETTINGS) != 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.
if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) && !ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) && !ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) && !ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_SETTINGS)) {
showMessageOKCancel("You need to allow access to few permissions so that the app can work as expected.",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_SETTINGS},
REQUEST_RUNTIME_PERMISSION);
}
});
return;
}
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_SETTINGS},
REQUEST_RUNTIME_PERMISSION);
return;
}
}
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(getBaseContext());
locationProvider.getLastKnownLocation()
.subscribe(new Action1<Location>() {
#Override
public void call(Location location) {
currentLatDouble = location.getLatitude();
currentLngDouble = location.getLongitude();
Toast.makeText(getBaseContext(), "User's location retrieved using library for android M in btnRetryGpsEvents()", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(getBaseContext(), "called from btnRetryGpsEvents() - GPS available", Toast.LENGTH_SHORT).show();
}
});
}
After running the above code, the toast due to this code is shown: Toast.makeText(getBaseContext(), "called from btnRetryGpsEvents() - GPS available", Toast.LENGTH_SHORT).show(); which means that this is getting executed, but the toast just above it viz.: Toast.makeText(getBaseContext(), "User's location retrieved using library for android M in btnRetryGpsEvents()", Toast.LENGTH_SHORT).show(); is not shown which means it doesn't gets executed!
How this can happen? What's going wrong here????
Please let me know.
P.S.: This problem is occuring only in Android M and above.
Please check code inside ReactiveLocationProvider. I think it implements LocationListener. Guessing that getLastLocation called inside. It will give location only if last location available. Or please provide code so we can check.
I have added in my activity -location permission check on run time- but I still get the error that tell me to add the permission check...
here is my code. In Oncreate () I have added:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
bPermissionGranted = checkLocationPermission();
}
In on onConnected:
public void onConnected(Bundle bundle) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (bPermissionGranted) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
handleNewLocation(location);
} else {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
handleNewLocation(location);
}
}
}
And the two method:
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
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;
}
}
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.
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
handleNewLocation(location);
} 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
}
}
And it still mark the follow with red error:
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Well your code is somewhat fine. Don't check for permission in onCreate. Check it in your onConnected() method because its possible that the user has not granted the permission yet and onConnected() is executed before.
Then when you receive the permission result in onRequestPermissionsResult(), then start fetching the location updates if the result is positive.
Also an advice -
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
This piece of code is redundant. Android only requires run time permissions in Android M and above so your permission check code would only be executed if the Android version is above M else it won't execute.
I am trying to make an application that sends location updates of a user after every five minutes. I suppose my code is working just fine but i get an error regarding the permissions that are being used by the application. I am pretty sure that i have added the permissions in the manifest file. Can someone tell me what's wrong? Here is my code.
MainActivity.java
LocationManager locationManager ;
String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting LocationManager object
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider,5*60*1000,0,this);
if(location!=null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// Getting reference to TextView tv_longitude
TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
// Getting reference to TextView tv_latitude
TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
// Setting Current Longitude
tvLongitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
tvLatitude.setText("Latitude:" + location.getLatitude() );
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
I am getting an error as Call requires permission which may be rejected by user in these lines-
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider,5*60*1000,0,this);
My AndroidManifest is like this
<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"/>
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Which SDK do you use?
If you use Marshmallow, then you need to check that the user has granted permission for every location call.
Take a look Here.
You should do something like this:
if (ContextCompat.checkSelfPermission( this,android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED )
{
ActivityCompat.requestPermissions(
this,
new String [] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION
);
}
request permission if you dont have it already.
check the link above for more info.
Try my code:
public class MainActivity extends AppCompatActivity {
/* GPS Constant Permission */
private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 12;
/* Position */
private static final int MINIMUM_TIME = 10000; // 10s
private static final int MINIMUM_DISTANCE = 50; // 50m
/* GPS */
private String mProviderName;
private LocationManager mLocationManager;
private LocationListener mLocationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Get the best provider between gps, network and passive
Criteria criteria = new Criteria();
mProviderName = mLocationManager.getBestProvider(criteria, true);
// API 23: we have to check if ACCESS_FINE_LOCATION and/or ACCESS_COARSE_LOCATION permission are granted
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// No one provider activated: prompt GPS
if (mProviderName == null || mProviderName.equals("")) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
// At least one provider activated. Get the coordinates
switch (mProviderName) {
case "passive":
mLocationManager.requestLocationUpdates(mProviderName, MINIMUM_TIME, MINIMUM_DISTANCE, this);
Location location = mLocationManager.getLastKnownLocation(mProviderName);
break;
case "network":
break;
case "gps":
break;
}
// One or both permissions are denied.
} else {
// The ACCESS_COARSE_LOCATION is denied, then I request it and manage the result in
// onRequestPermissionsResult() using the constant MY_PERMISSION_ACCESS_FINE_LOCATION
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_ACCESS_COARSE_LOCATION);
}
// The ACCESS_FINE_LOCATION is denied, then I request it and manage the result in
// onRequestPermissionsResult() using the constant MY_PERMISSION_ACCESS_FINE_LOCATION
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this,
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
MY_PERMISSION_ACCESS_FINE_LOCATION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_ACCESS_COARSE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
} else {
// permission denied
}
break;
case MY_PERMISSION_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
} else {
// permission denied
}
break;
}
}
}
}
Source: LINK
This worked for me
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) {
Toast.makeText(YourService.this, "First enable LOCATION ACCESS in settings.", Toast.LENGTH_LONG).show();
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, listener);
Here are the bunch of steps you need to perform to fix this
Main Activity .java
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates
(locationManager.requestLocationUpdates(provider,5*60*1000,0,this);
}//end of if
Now you also need to update your build.gradle
dependencies{
------------- //your pre-generated code
compile 'com.android.support:support-v4:23.0.1'
}
this is what Android.Developers say about it.
And don't forget to give permissions from application settings if you're using an emulator because it may not prompt for such