Unable to get location on Android - android

I want to get the location of the device at app startup.
I have been looking through the docs, trying to figure out what goes wrong, but I can't seem to find it. onLocationChanged is never called.
private void getLocation() {
// Connected to Google API
// Create location request with minimum interval of a minute, and normal of an hour
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setFastestInterval(1000 * 60);
mLocationRequest.setInterval(1000 * 60 * 60);
// Request permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{"ACCESS_FINE_LOCATION"}, MY_PERMISSION_LOCATION_CODE);
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_LOCATION_CODE: {
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
else {
TextView loading = (TextView)findViewById(R.id.connecting_text);
loading.setText("Please enable Location under Settings > Apps > Beet > Permissions.");
loading.setTextSize(20);
}
break;
}
}
}
public void onLocationChanged(Location location) {
System.out.println("GETLOCATION1 ________________");
mLastLocation = location;
System.out.println(location.getLatitude() + " - " + location.getLongitude() + " ________________");
}

Try getting permission like this: it works in my case
if (!checkIfAlreadyhavePermission()) {
ActivityCompat.requestPermissions(this, new String[]{"ACCESS_FINE_LOCATION"}, MY_PERMISSION_LOCATION_CODE);
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED;
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_LOCATION_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Call_location_updates();
} else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.gps_permission), Toast.LENGTH_LONG).show();
finish();
}
break;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Also create your LocationRequest object like this:
private final int INTERVAL = 5000;
private final int FAST_INTERVAL = 1000;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FAST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
public void Call_location_updates(){
Location location = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (location != null) {
onLocationChanged(location);
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onLocationChanged(Location location) {
//do what u want with location
}

Related

Getting user current location using fused location provider

I am using google play service location api (fused location provider) to get user current location. In some cases it takes too much time to return the results and sometimes it takes quite less time to return the reslts for the same device. In both cases user was indoor. I could not understand which is the reason behind this scenario.
public class SelfAttendanceFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
OnMapReadyCallback, GoogleMap.OnMapClickListener {
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
private static final int MY_PERMISSIONS_REQUEST = 1;
private static Double LATITUDE_DHAKA;
private static Double LONGITUDE_DHAKA;
LoadingDialog mLoadingDialog;
double latitude = 0;
double longitude = 0;
Handler mHandler;
CountDownTimer countDownTimer;
FusedLocationProviderClient mFusedLocationClient;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
LocationCallback mLocationCallback;
LocationManager locationManager;
SupportMapFragment mapFragment;
Location location;
private GoogleMap mMap;
private String address;
private String remarks = "";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_self_attendance, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/*if (!checkPermissionGranted()) {
askForPermission();
}*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED ) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST);
} else {
startAction();
}
} else {
startAction();
}
}
private void startAction(){
mLoadingDialog = new LoadingDialog(getContext(), getString(R.string.fetching_location));
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getContext());
locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
doCheckPermissionForGps();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> locationList = locationResult.getLocations();
for (Location loc : locationList) {
if (loc.getLatitude() != 0 && loc.getLongitude() != 0) {
location = loc;
checkLocationandAddToMap();
break;
}
}
}
};
}
private void doCheckPermissionForGps() {
Boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGpsEnabled && mGoogleApiClient != null) {
requestLocationUpdates();
} else if (mGoogleApiClient == null) {
buildGoogleApiClient();
} else if (!isGpsEnabled) {
displayLocationSettingsRequest(getContext());
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(10);
mLocationRequest.setFastestInterval(10 / 2);
}
private String getAddressByLattitudeAndLongitude() {
String address;
try {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(getContext(), Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 5); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
if (address.isEmpty()) {
address = addresses.get(0).getLocality();
}
} catch (Exception ex) {
address = "";
}
return address;
}
private void displayLocationSettingsRequest(Context context) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(getActivity(), REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
#SuppressLint("MissingPermission")
private void requestLocationUpdates() {
if(isAdded() && getActivity() != null){
mLoadingDialog.showDialogWithText("Fetching location using GPS...");
}
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
switch (resultCode) {
case -1:
requestLocationUpdates();
break;
case 0:
displayLocationSettingsRequest(getContext());
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
displayLocationSettingsRequest(getContext());
} else {
requestLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onDestroy() {
super.onDestroy();
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
try{
mMap = googleMap;
mMap.clear();
LATITUDE_DHAKA = 23.777176;
LONGITUDE_DHAKA = 90.399452;
try {
boolean success = mMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
getContext(), R.raw.style_map));
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(LATITUDE_DHAKA, LONGITUDE_DHAKA)).zoom(10) // Sets the zoom
// Sets the orientation of the camera to east
.build();
if (mMap != null)
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
doCheckPermissionForGps();
return false;
}
});
View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 0, 100);
} catch (Exception ex){
}
}
private void checkLocationandAddToMap() {
//MarkerOptions are used to create a new Marker.You can specify location, title etc with MarkerOptions
if (location != null) {
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(17) // Sets the zoom
// Sets the orientation of the camera to east
.build();
if (mMap != null)
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
}
}
#Override
public void onMapClick(LatLng latLng) {
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
startAction();
} else {
CustomSnackbarError.showMessageFromFragment(getContext(),"Permission is necessary" +
" to enable this feature");
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST);
}
}
/*#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED
*//* && grantResults[2] == PackageManager.PERMISSION_GRANTED
&& grantResults[3] == PackageManager.PERMISSION_GRANTED
&& grantResults[4] == PackageManager.PERMISSION_GRANTED
&& grantResults[5] == PackageManager.PERMISSION_GRANTED
&& grantResults[6] == PackageManager.PERMISSION_GRANTED
&& grantResults[7] == PackageManager.PERMISSION_GRANTED*//*
) {
//checkForUpdate();
startAction();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}*/
private boolean checkPermissionGranted() {
/* if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_NETWORK_STATE)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.INTERNET)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}*/
/* if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}*/
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
return true;
}
private void askForPermission() {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{
/*Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.INTERNET,
Manifest.permission.CALL_PHONE,
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,*/
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
},
MY_PERMISSIONS_REQUEST);
}
#Override
public void onDestroyView() {
super.onDestroyView();
dismisLoadingDialog();
}
private void dismisLoadingDialog(){
if(mLoadingDialog != null && mLoadingDialog.isShowing()){
mLoadingDialog.dismiss();
}
}
}
Most of the time GPS provider takes much time to fetch location when the user is within the building. In that case, you must have to fetch location from the network provider for faster results. GPS works very well outside the building but has trouble to fetch location from within. Please allow fetching location from both network & GPS provider for improved result.
The way android has implemented and created this fusedlocationprovider library is it takes two types of location updates:
1 -> Network Based
2 -> GPS
As when user try to fetch the location from indoor or any place where GPS has no much space for getting location from satellite it uses network.
so, when you are working indoor you will see that it is troubling fetching location. But as you said sometimes it takes lesser time and sometimes it takes much time.
The possible scenario is Whenever you request for location it will go and try to find the location if there is already location taken by other application and if there is location you will get it. Otherwise it will try to find the location by its own and next time you search for it as it has already it will give you directly.
And you have used GPS Provider, use Network provider as well.
Let me know if it helps. Thanks
Add the below code for getting the current location faster using fused location - FusedLocationProviderClient :
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val PERMISSION_ID = 1000
private lateinit var mFusedLocationClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
getCurrentLocation()
}
private fun getCurrentLocation() {
if (isLocationEnabled()) {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions()
return
}
val tokenSource = CancellationTokenSource()
val token = tokenSource.token
mFusedLocationClient.getCurrentLocation(PRIORITY_HIGH_ACCURACY, token)
.addOnCompleteListener(this) { task ->
val location: Location? = task.result
Toast.makeText(
this,
"${location!!.latitude} and ${location.longitude}",
Toast.LENGTH_SHORT
).show()
}
} else {
Toast.makeText(this, "Please turn on location", Toast.LENGTH_LONG).show()
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
}
private fun isLocationEnabled(): Boolean {
val locationManager: LocationManager =
getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
)
}
private fun requestPermissions() {
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
),
PERMISSION_ID
)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSION_ID) {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
getCurrentLocation()
}
}
}
}
build.gradle
implementation 'com.google.android.gms:play-services-location:20.0.0'

Android location app only running properly after clean install

I wrote this app for an assignment, but for some reason two of the questions will only run properly once, and only after the app is installed.
e.g. If i install the app and run Question 1a then it will work perfectly. If I try and run Question 2 after that, or run Question 1a again, it won't work unless I uninstall and reinstall the apk. It also works the other way around, so if I run Question 2 first then Question 1a won't work and Question 2 won't work if I try and run it again.
I don't get any errors or crashes, it just doesn't do anything. It's strange though because Question 1b works perfectly all the time and is very similar to both Question 1a and Question 2 except it uses a Google Map.
Edit: I just realized that the map in question 1b doesn't work anymore (Google Maps API authorization failed) but it does update the address properly in the TextView, now if only I could figure out why the TextView updates in Question 1b but not the other two.
Any help would be greatly appreciated!
The code is as follows:
Question 1a:
public class Question1a extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private TextView txtAddress;
private GoogleApiClient client;
private LocationRequest locationRequest;
public static final int REQUEST_MULTIPLE_PERMISSIONS_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1a);
txtAddress = (TextView) findViewById(R.id.addressEdit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkPermissions();
}
}
//creates a location request object and sets the location request intervals
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i)
{
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
//Gets address and displays it in a TextView
#Override
public void onLocationChanged(Location location)
{
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
if(addresses == null)
{
Toast.makeText(this, "No address found", Toast.LENGTH_SHORT).show();
}
else
{
Address address = addresses.get(0);
String finalAddress = "Address: ";
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
{
finalAddress = finalAddress + address.getAddressLine(i);
}
txtAddress.setText(finalAddress);
}
}
//build the API client
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
//Checks if the app has the required permissions to run (Location permissions)
public boolean checkPermissions()
{
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case REQUEST_MULTIPLE_PERMISSIONS_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission has been granted
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
//if client is null(there is no Google API Client) this calls the method to build the Google API Client
if (client == null)
{
buildGoogleApiClient();
}
}
}
else
{
Toast.makeText(this, "Permissions were denied", Toast.LENGTH_SHORT).show();
}
}
}
}
Question 1b:
public class Question1b extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
{
private TextView txtAddress;
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentLocationMarker;
public static final int REQUEST_MULTIPLE_PERMISSIONS_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1b);
txtAddress = (TextView) findViewById(R.id.locationAddressEdit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkPermissions();
}
// 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_MULTIPLE_PERMISSIONS_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission has been granted
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
//if client is null(there is no Google API Client) this calls the method to build the Google API Client
if (client == null)
{
buildGoogleApiClient();
}
}
}
else
{
Toast.makeText(this, "Permissions were denied", Toast.LENGTH_SHORT).show();
}
}
}
//if the app has the right permissions then it will build the API client and enable location services when the map is ready
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
//creates a location request object and sets the location request intervals
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i)
{
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
//Moves the marker when location changes
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
if (currentLocationMarker != null)
{
currentLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
currentLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
if(addresses == null)
{
Toast.makeText(this, "No address found", Toast.LENGTH_SHORT).show();
}
else
{
Address address = addresses.get(0);
String finalAddress = "Address: ";
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
{
finalAddress = finalAddress + address.getAddressLine(i);
}
txtAddress.setText(finalAddress);
}
}
//Checks if the app has the required permissions to run (Location permissions & SMS permissions)
public boolean checkPermissions()
{
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
return false;
}
else
{
return true;
}
}
//build the API client
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
}
Question 2:
public class Question2 extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private TextView txtAddress;
private GoogleApiClient client;
private LocationRequest locationRequest;
public static final int REQUEST_MULTIPLE_PERMISSIONS_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
txtAddress = (TextView) findViewById(R.id.addressEdit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkPermissions();
}
}
//creates a location request object and sets the location request intervals
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i)
{
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
//Gets address using geocoder and displays it in a TextView
#Override
public void onLocationChanged(Location location)
{
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
if(addresses == null)
{
Toast.makeText(this, "No address found", Toast.LENGTH_SHORT).show();
}
else
{
Address address = addresses.get(0);
String finalAddress = "Address: ";
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
{
finalAddress = finalAddress + address.getAddressLine(i);
}
txtAddress.setText(finalAddress);
}
}
//build the API client
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
//Checks if the app has the required permissions to run (Location permissions & SMS permissions)
public boolean checkPermissions()
{
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case REQUEST_MULTIPLE_PERMISSIONS_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission has been granted
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
//if client is null(there is no Google API Client) this calls the method to build the Google API Client
if (client == null)
{
buildGoogleApiClient();
}
}
}
else
{
Toast.makeText(this, "Permissions were denied", Toast.LENGTH_SHORT).show();
}
}
}
public void sendMyLocation(View v)
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+27718831284", null, "Your location is: " + txtAddress.getText(), null, null);
}
}

How to properly update location when requesting permission at run time?

I am trying to update the users location every second (every second I want a log message to appear which contains the actual position of the user), for this I have to ask the user at run time if he wants to allow the app to get access to his position only once (I have to ask because API 24 requires this). After the user has accepted the app does not ask again.
But onLocationChanged does not get called.
#Override
protected void onCreate(Bundle bundle) {
//initializing UI
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
mLocationRequest.setInterval(1000);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
return;
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == 1) {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults.length > 0) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
Log.i("LOCATION", location.toString());
}

Google Location Services getLastLocation gets null when launching app for the first time

So i want to display my latitude and longitude of the position, however it shows me only when i launch the app again.
When i install the app, and launch it for the first time there is no position received.
What is the simple way to get the current location for the first time? What i am doing wrong? I run this on emulator with API 24.
Here is my code:
private final static String LOG_TAG = MainActivity.class.getName();
private GoogleApiClient googleApiClient;
private Location lastLocation;
private LocationRequest locationRequest;
private TextView locationLatitude;
private TextView locationLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationLatitude = (TextView) findViewById(R.id.latitude_text);
locationLongitude = (TextView) findViewById(R.id.longitude_text);
buildGoogleApiClient();
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
private void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(LOG_TAG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if(Build.VERSION.SDK_INT < 21){
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
else {
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}, 1);
}
else{
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
}
if(lastLocation != null){
locationLatitude.setText(String.valueOf(lastLocation.getLatitude()));
locationLongitude.setText(String.valueOf(lastLocation.getLongitude()));
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 1){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
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) {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
}
}
}
#Override
public void onConnectionSuspended(int i) {
Log.d(LOG_TAG, "onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(LOG_TAG, "onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
Log.d(LOG_TAG, "onLocationChanged");
locationLatitude.setText(String.valueOf(location.getLatitude()));
locationLongitude.setText(String.valueOf(location.getLongitude()));
}
You never request location updates.
Try this:
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(LOG_TAG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
if(Build.VERSION.SDK_INT < 21){
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
else {
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}, 1);
}
else{
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
}
if(lastLocation != null){
locationLatitude.setText(String.valueOf(lastLocation.getLatitude()));
locationLongitude.setText(String.valueOf(lastLocation.getLongitude()));
}
}

Android FusedLocationApi Location Service Not Working Properly using Runtime Permission API 23

Can anybody help me to solve problem:
onConnected() method why my
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
code not executing; and retrun from checkSelfPermission()
what can i do to work FusedLocationApi properly in this code
my code is below
public class JMSCLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private final String TAG = "MyAwesomeApp";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
// Check Permissions Now
private static final int REQUEST_LOCATION = 2;
//private final double radiusInMeters = 1609.34;
private final double radiusInMeters = 16.34;
LatLng firstLatLong;
Location fLoc;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "GoogleApiClient connection has STARTED");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
firstLatLong = new LatLng(0, 0);
Log.i(TAG, "GoogleApiClient connection has STARTED");
}
#Override
public void onDestroy() {
// disconnect the client.
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Connect the client.
if (mGoogleApiClient != null && !mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
Log.i(TAG, "GoogleApiClient mGoogleApiClient.connect();");
}
if (mGoogleApiClient.isConnected()) {
Log.i(TAG, "GoogleApiClient mGoogleApiClient.isConnected();");
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "GoogleApiClient connection has been suspend");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, "GoogleApiClient connection has failed");
}
#Override
public void onLocationChanged(Location mCurrentLocation) {
Log.i(TAG, "GoogleApiClient Location received: " + mCurrentLocation.toString());
//test outside
double mLatitude = mCurrentLocation.getLatitude();
double mLongitude = mCurrentLocation.getLongitude();
if(firstLatLong.latitude == 0.0 && firstLatLong.longitude == 0.0){
firstLatLong = new LatLng(mLatitude,mLongitude);
fLoc=new Location(mCurrentLocation);
}
float[] results = new float[1];
Location.distanceBetween(firstLatLong.latitude, firstLatLong.longitude,
mLatitude, mLongitude, results);
float distanceInMeters = fLoc.distanceTo(mCurrentLocation);
try{
if( distanceInMeters > radiusInMeters ){
Toast.makeText(getBaseContext(), "Outside, distance from center", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside, distance from center", Toast.LENGTH_LONG).show();
}
}catch (Exception ex){
ex.printStackTrace();
}
}
}
USE:
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_ID);
}else{
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
AND:
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_ID: {
for( int i = 0; i < permissions.length; i++ ) {
if( grantResults[i] == PackageManager.PERMISSION_GRANTED) {
Log.d("Permissions", "Permission Granted: " + permissions[i]);
} else if( grantResults[i] == PackageManager.PERMISSION_DENIED ) {
Log.d( "Permissions", "Permission Denied: " + permissions[i] );
}
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
You have to request the permissions. You are just checking whether your app has the permission.
You are ignoring the result of checkSelfPermission() in your code.
Read the comments, they are self explanatory.
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) {
// 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;
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
Read about requesting runtime permissions from :
https://developer.android.com/training/permissions/requesting.html#perm-request
http://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/
Edit 1
I think by ...but at compile time in service it's gives error for must use selfcheck permission you mean the Lint warnings.
You can suppress them by adding #SuppressWarnings("MissingPermission") on top of the method in which you are calling requestLocationUpdates().
But make sure you have are calling requestLocationUpdates() iff you have the permission for it (Mind the if..else block).

Categories

Resources