How do i call non activity class in MainActivity class? - android

I have Fused Location Api class which extends AppCompatActivity right now. I want to make it non-activity class and call it in MainActivity or in any other activity class. How can i do that? I am a newbie . So please any constructive criticism would be really appreciated.
public class GpsLocation extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private Location location;
private TextView locationTv;
private GoogleApiClient googleApiClient;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private LocationRequest locationRequest;
private static final long UPDATE_INTERVAL = 5000, FASTEST_INTERVAL = 5000; // = 5 seconds
// lists for permissions
private ArrayList<String> permissionsToRequest;
private ArrayList<String> permissionsRejected = new ArrayList<>();
private ArrayList<String> permissions = new ArrayList<>();
// integer for permissions results request
private static final int ALL_PERMISSIONS_RESULT = 1011;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_hotkey_navigation);
locationTv = findViewById(R.id.location);
// we add permissions we need to request location of the users
permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
permissionsToRequest = permissionsToRequest(permissions);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (permissionsToRequest.size() > 0) {
requestPermissions(permissionsToRequest.toArray(
new String[0]), ALL_PERMISSIONS_RESULT);
}
}
// we build google api client
googleApiClient = new GoogleApiClient.Builder(this).
addApi(LocationServices.API).
addConnectionCallbacks(this).
addOnConnectionFailedListener(this).build();
}
private ArrayList<String> permissionsToRequest(ArrayList<String> wantedPermissions) {
ArrayList<String> result = new ArrayList<>();
for (String perm : wantedPermissions) {
if (!hasPermission(perm)) {
result.add(perm);
}
}
return result;
}
private boolean hasPermission(String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
return true;
}
#Override
protected void onStart() {
super.onStart();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
if (!checkPlayServices()) {
locationTv.setText("You need to install Google Play Services to use the App properly");
}
}
#Override
protected void onPause() {
super.onPause();
// stop location updates
if (googleApiClient != null && googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
googleApiClient.disconnect();
}
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST);
} else {
finish();
}
return false;
}
return true;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
// Permissions ok, we get last location
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
locationTv.setText("Latitude : " + location.getLatitude() + "\nLongitude : " + location.getLongitude());
}
startLocationUpdates();
}
private void startLocationUpdates() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "You need to enable permissions to display location !", Toast.LENGTH_SHORT).show();
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
locationTv.setText("Latitude : " + location.getLatitude() + "\nLongitude : " + location.getLongitude());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode) {
case ALL_PERMISSIONS_RESULT:
for (String perm : permissionsToRequest) {
if (!hasPermission(perm)) {
permissionsRejected.add(perm);
}
}
if (permissionsRejected.size() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
new AlertDialog.Builder(GpsLocation.this).
setMessage("These permissions are mandatory to get your location. You need to allow them.").
setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
requestPermissions(permissionsRejected.
toArray(new String[0]), ALL_PERMISSIONS_RESULT);
}
}).setNegativeButton("Cancel", null).create().show();
return;
}
}
} else {
if (googleApiClient != null) {
googleApiClient.connect();
}
}
break;
}
}
}
I need to get its gps coordinates and send it to MainActivity class.So please help me. Any help would be much really appreciated.

why are you extending AppCompat at all if you want a regular class? Create a normal class and instantiate it in your activity.
What exactly are you trying to do in this class, that it cant be a method in your Activity?
The fused Location Client can me created anywhere by calling
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

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'

fused location provider give wrong location

i am using Fusedlocationprovider get my current location, Some times I get the current location currently ,but some times give wrong location ,but near the current location. what is the reason, I am new to android , help me to solve this problem.thank you.
This is the my code :
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private double myLatitude;
private double myLongitude;
private static final int MY_PERMISSION_REQUEST_FINE_LOCATION = 101;
private static final int MY_PERMISSION_REQUEST_COARSE_LOCATION = 102;
private boolean permissionIsGranted = false;
String phonenumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if (extras != null) {
phonenumber = extras.getString("key11");
getIntent().removeExtra("key11");
}
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
locationRequest = new LocationRequest();
locationRequest.setInterval(10 * 1000);
locationRequest.setFastestInterval(15 * 1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(Bundle bundle) {
requestLocationUpdates();
}
private void requestLocationUpdates() {
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.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_REQUEST_FINE_LOCATION);
} else {
permissionIsGranted = true;
}
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phonenumber, null, "*-"+String.valueOf(myLatitude)+"#"+String.valueOf(myLongitude)+"#", null, null);
System.exit(0);
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
if (permissionIsGranted) {
if (googleApiClient.isConnected()) {
requestLocationUpdates();
}
}
}
#Override
protected void onPause() {
super.onPause();
if (permissionIsGranted)
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
#Override
protected void onStop() {
super.onStop();
if (permissionIsGranted)
googleApiClient.disconnect();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_REQUEST_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted
permissionIsGranted = true;
} else {
//permission denied
permissionIsGranted = false;
Toast.makeText(getApplicationContext(), "This app requires location permission to be granted", Toast.LENGTH_SHORT).show();
}
break;
case MY_PERMISSION_REQUEST_COARSE_LOCATION:
// do something for coarse location
break;
}
}
}
Please help me Android Pro Developers Solve my error!

GPS enabled? always false

Try to check if GPS is enabled on SDK 25.
Do this:
LocationManager manager = (LocationManager)
view.getContext().getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled =
manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
it always returns false. Then I start startActivityForResult as:
view.getFragment().startActivityForResult(intent,
Constants.GPS_ENABLE);
this opens me settings windows, I swtich GPS on, push back button, go back to fragment and got:
1. On Activity Result responsecode 0 (always)
2. GPS enabled checking again say "false", as it is not enabled.
Moreover, I tried this:
String provider =
Secure.getString(view.getContext().getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){}
And as google tutorial says task.locationsettings.
All tries always say GPS disabled and onActivityResult always 0.
I need both: know when GPS enabled/disaabled and recieve correct resultCode in onActivityResult(onActivityResult is called in Fragment and it is called succesfully, but with wrong responseCode in it)
What I do wrong?
UPDATE
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("ACTIVITY RESULT", "RqC:" + requestCode + "; ReSC" + resultCode);
if (requestCode == Constants.GPS_ENABLE && resultCode == RESULT_OK) {
presenter.getGPS();
} else {
Log.e("ON ACTIVITY RESULT", "Не дал мне прав");
}
}
public void onPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Constants.GPS_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getGPS();
}
default:
requestPermissions();
}
}
public void checkGpsEnabled(String caller) {
Log.e("I AM CALLED FROM", caller);
LocationManager manager = (LocationManager) view.getContext().getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGpsEnabled) {
Log.e("CheckGPSENABLED", "Включен");
getGPS();
} else {
Log.e("CheckGPSENABLED", "ВЫЫЫключен");
Toast.makeText(view.getContext(), "Для продолжения работы приложения, пожалуйста, включите GPS", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
view.getFragment().startActivityForResult(intent, Constants.GPS_ENABLE);
}
}
#SuppressLint("MissingPermission")
public void getGPS() {
Log.e(getClass().getName(), "getGPSFUSE");
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(view.getViewActivity());
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(view.getViewActivity(), location -> {
if (location != null) {
Log.e("LOCATION", location.toString());
//Если получил координаты, вернуть
} else {
requestNewLocation();
}
});
}
#SuppressLint("MissingPermission")
public void requestNewLocation() {
Log.e(getClass().getName(), "request new location");
mLocationRequest = new LocationRequest();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
Toast.makeText(view.getContext(), "Координаты не найдены", Toast.LENGTH_SHORT).show();
return;
}
for (Location location : locationResult.getLocations()) {
Log.e("NEW", location.toString());
}
}
};
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback,
null /* Looper */);
}
}
public void requestPermissions() {
if (ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(view.getViewActivity(), new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET}, Constants.GPS_PERMISSION);
} else {
checkGpsEnabled("request");
}
}
I think you are too much confused in using FusedLocation API and GPS etc. Also in your question code snippet I dont see where you are acquiring runtime permission from user since your build target is 25. So you need to ask for some permissions. Like location permissions. here is a link of runtime permissions
Your manifest must contain these permissions and you must acquire run time permissions.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Here the below code is for a quick over view. This snippet is taken from this link. And I think this link is also good for you.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
protected static final String TAG = "location-updates-sample";
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
private final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
private final static String LOCATION_KEY = "location-key";
private final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private static final int REQUEST_CHECK_SETTINGS = 10;
private ActivityMainBinding mBinding;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
private Boolean mRequestingLocationUpdates;
private String mLastUpdateTime;
private String mLatitudeLabel;
private String mLongitudeLabel;
private String mLastUpdateTimeLabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mLatitudeLabel = getResources().getString(R.string.latitude_label);
mLongitudeLabel = getResources().getString(R.string.longitude_label);
mLastUpdateTimeLabel = getResources().getString(R.string.last_update_time_label);
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
updateValuesFromBundle(savedInstanceState);
buildGoogleApiClient();
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
Log.i(TAG, "Updating values from bundle");
if (savedInstanceState != null) {
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
REQUESTING_LOCATION_UPDATES_KEY);
setButtonsEnabledState();
}
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
updateUI();
}
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void startUpdatesButtonHandler(View view) {
clearUI();
if (!isPlayServicesAvailable(this)) return;
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
} else {
return;
}
if (Build.VERSION.SDK_INT < 23) {
setButtonsEnabledState();
startLocationUpdates();
return;
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
setButtonsEnabledState();
startLocationUpdates();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
showRationaleDialog();
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
}
public void stopUpdatesButtonHandler(View view) {
if (mRequestingLocationUpdates) {
mRequestingLocationUpdates = false;
setButtonsEnabledState();
stopLocationUpdates();
}
}
private void startLocationUpdates() {
Log.i(TAG, "startLocationUpdates");
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
}
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way
// to fix the settings so we won't show the dialog.
break;
}
}
});
}
private void setButtonsEnabledState() {
if (mRequestingLocationUpdates) {
mBinding.startUpdatesButton.setEnabled(false);
mBinding.stopUpdatesButton.setEnabled(true);
} else {
mBinding.startUpdatesButton.setEnabled(true);
mBinding.stopUpdatesButton.setEnabled(false);
}
}
private void clearUI() {
mBinding.latitudeText.setText("");
mBinding.longitudeText.setText("");
mBinding.lastUpdateTimeText.setText("");
}
private void updateUI() {
if (mCurrentLocation == null) return;
mBinding.latitudeText.setText(String.format("%s: %f", mLatitudeLabel,
mCurrentLocation.getLatitude()));
mBinding.longitudeText.setText(String.format("%s: %f", mLongitudeLabel,
mCurrentLocation.getLongitude()));
mBinding.lastUpdateTimeText.setText(String.format("%s: %s", mLastUpdateTimeLabel,
mLastUpdateTime));
}
protected void stopLocationUpdates() {
Log.i(TAG, "stopLocationUpdates");
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setButtonsEnabledState();
startLocationUpdates();
} else {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
mRequestingLocationUpdates = false;
Toast.makeText(MainActivity.this, "このアプリの機能を有効にするには端末の設定画面からアプリの位置情報パーミッションを有効にして下さい。", Toast.LENGTH_SHORT).show();
} else {
showRationaleDialog();
}
}
break;
}
}
}
private void showRationaleDialog() {
new AlertDialog.Builder(this)
.setPositiveButton("許可する", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
})
.setNegativeButton("しない", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "位置情報パーミッションが許可されませんでした。", Toast.LENGTH_SHORT).show();
mRequestingLocationUpdates = false;
}
})
.setCancelable(false)
.setMessage("このアプリは位置情報の利用を許可する必要があります。")
.show();
}
public static boolean isPlayServicesAvailable(Context context) {
// Google Play Service APKが有効かどうかチェックする
int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS) {
GoogleApiAvailability.getInstance().getErrorDialog((Activity) context, resultCode, 2).show();
return false;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
break;
}
break;
}
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onResume() {
super.onResume();
isPlayServicesAvailable(this);
// Within {#code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onPause() {
super.onPause();
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
#Override
protected void onStop() {
stopLocationUpdates();
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "onConnected");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
Toast.makeText(this, getResources().getString(R.string.location_updated_message), Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime);
super.onSaveInstanceState(savedInstanceState);
}
}

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);
}
}

wait till the GPS is enabled before getting the lat and long value in FusedLocationAPI

I am trying to get current location using FusedLocationAPI in my application. It works just fine in both android API>23 and <23. The issue is in case of GPS is not enabled, the app prompts the user to enable the GPS and after that the location returns null. But while restarting the app, it works just fine. In case of GPS not being turned OFF, the app just works fine. Is there any way that the app can wait for the GPS to be enabled before getting the location? below I am posting my code. Please have a look.
Inside onCreate():
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!statusOfGPS) {
displayPromptForEnablingGPS(this);
}
Log.d("permipart", "before");
if(CheckingPermissionIsEnabledOrNot())
{
Toast.makeText(MainActivity.this, "All Permissions Granted Successfully", Toast.LENGTH_LONG).show();
}
else {
RequestMultiplePermission();
}
if(Build.VERSION.SDK_INT<= 23)
{
buildGoogleApiClient();
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
Log.d("permipart", "out");
Other methods:
#Override
public void onLocationChanged(Location location) {
Log.d("onconnectedlocchange","called");
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
if (!String.valueOf(lat).equals("0.0"))
{
latitudeVal = location.getLatitude();
longitudeVal = location.getLongitude();
Log.e("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if(CheckingPermissionIsEnabledOrNot())
{
Toast.makeText(MainActivity.this, "All Permissions Granted Successfully", Toast.LENGTH_LONG).show();
}
// If, If permission is not enabled then else condition will execute.
else {
//Calling method to enable permission.
RequestMultiplePermission();
}
Log.d("onconnected","called");
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Update location every second
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
else
{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();
if (!String.valueOf(lat).equals("0.0")){
latitudeVal = mLastLocation.getLatitude();
longitudeVal = mLastLocation.getLongitude();
Log.e("Lat and Lng", String.valueOf(latitudeVal)+ longitudeVal);
}
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public void displayPromptForEnablingGPS(final Activity activity) {
final android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
final String message = "Do you want open GPS setting?";
builder.setMessage(message)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
activity.startActivity(new Intent(action));
d.dismiss();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.cancel();
}
});
builder.create().show();
}
String[] permissions = new String[]{ACCESS_FINE_LOCATION,
ACCESS_COARSE_LOCATION, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE };
//Permission function starts from here
private void RequestMultiplePermission() {
// Creating String Array with Permissions.
Log.d("permipart", "RequestMultiplePermission");
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{
READ_EXTERNAL_STORAGE,
WRITE_EXTERNAL_STORAGE,
ACCESS_FINE_LOCATION,
ACCESS_COARSE_LOCATION
}, RequestPermissionCode);
}
private boolean checkPermission() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(this,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),10 );
Log.d("permissionissue","no");
return false;
}
Log.d("permissionissue","yes");
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Log.d("permipart", "onRequestPermissionsResult");
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean CameraPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean RecordAudioPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean SendSMSPermission = grantResults[2] == PackageManager.PERMISSION_GRANTED;
boolean GetAccountsPermission = grantResults[3] == PackageManager.PERMISSION_GRANTED;
if (CameraPermission && RecordAudioPermission && SendSMSPermission && GetAccountsPermission) {
Log.d("permipart", "done");
buildGoogleApiClient();
Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_LONG).show();
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
else {
Toast.makeText(MainActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
/**
* Checking permission is enabled or not using function starts from here.
*
*/
public boolean CheckingPermissionIsEnabledOrNot() {
int FirstPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
int SecondPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
int ThirdPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
int ForthPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_COARSE_LOCATION);
return FirstPermissionResult == PackageManager.PERMISSION_GRANTED &&
SecondPermissionResult == PackageManager.PERMISSION_GRANTED &&
ThirdPermissionResult == PackageManager.PERMISSION_GRANTED &&
ForthPermissionResult == PackageManager.PERMISSION_GRANTED ;
}
You need to recieve the broadcast of the GPS status something like this:
public class GpsLocationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
// here you can get the location or start a service to get it.
// example
// Intent getLocationService = new Intent(context,YourService.class);
// context.startService(getLocationService);
}
}
}
update
according to comment below
use this in your code
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(manager.isProviderEnabled( LocationManager.GPS_PROVIDER)){
// it is enabled
}else{
// it is not
}
Use my code, it will ask the user to turn on GPS if it is turned off. It will never return you anything until GPS turned on.
Note: you have to get location permission before using it for marshmallow and above mobiles.
Try this:
#SuppressWarnings("MissingPermission")
public class LocationFinder implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public static final String TAG = "LocationFinder";
private static final String BROADCAST_GPS_REQ = "LocationFinder.GPS_REQ";
private static final String KEY_GPS_REQ = "key.gps.req";
private static final int GPS_REQUEST = 2301;
private Activity activity;
private FinderType finderType;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private long updateInterval;
private long fastestInterval;
private GpsRequestListener gpsRequestListener;
private LocationUpdateListener locationUpdateListener;
public LocationFinder(Activity activity, FinderType finderType) {
this.activity = activity;
this.finderType = finderType;
}
private void connectGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(activity)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
}
private void createLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(updateInterval);
locationRequest.setFastestInterval(fastestInterval);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int intExtra = intent.getIntExtra(KEY_GPS_REQ, 0);
switch (intExtra) {
case Activity.RESULT_OK:
try {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, LocationFinder.this);
} catch (Exception e) {
e.printStackTrace();
}
gpsRequestListener.gpsTurnedOn();
break;
case Activity.RESULT_CANCELED:
gpsRequestListener.gpsNotTurnedOn();
}
}
};
public void gpsRequestCallback(GpsRequestListener gpsRequestListener) {
this.gpsRequestListener = gpsRequestListener;
LocalBroadcastManager.getInstance(activity).registerReceiver(receiver, new IntentFilter(BROADCAST_GPS_REQ));
}
public void config(long updateInterval, long fastestInterval) {
this.updateInterval = updateInterval;
this.fastestInterval = fastestInterval;
}
public void find(LocationUpdateListener listener) {
this.locationUpdateListener = listener;
createLocationRequest();
connectGoogleApiClient();
}
private void find() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult) {
Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, LocationFinder.this);
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(activity, GPS_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.d(TAG, "No GPS Hardware");
break;
}
}
});
}
public void stopFinder() {
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
googleApiClient.disconnect();
}
try {
activity.unregisterReceiver(receiver);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(TAG, "GoogleApiClient: Connected");
find();
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "GoogleApiClient: onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "GoogleApiClient: onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
if (finderType != FinderType.TRACK)
stopFinder();
locationUpdateListener.onLocationUpdate(new LatLng(location.getLatitude(), location.getLongitude()));
}
public void setGpsRequestListener(GpsRequestListener gpsRequestListener) {
this.gpsRequestListener = gpsRequestListener;
}
public static void onRequestResult(Activity activity, int requestCode, int resultCode) {
if (requestCode == GPS_REQUEST) {
Intent intent = new Intent(BROADCAST_GPS_REQ);
intent.putExtra(KEY_GPS_REQ, resultCode);
LocalBroadcastManager.getInstance(activity).sendBroadcast(intent);
}
}
public enum FinderType {
// It will update the current GPS location once.
GPS,
//It will update the user location continuously.
TRACK
}
public interface LocationUpdateListener {
void onLocationUpdate(LatLng latLng);
}
public interface GpsRequestListener {
void gpsTurnedOn();
void gpsNotTurnedOn();
}
}
To get location update initialize the class like this:
public class MyActivity extends AppCompatActivity implements
LocationFinder.GpsRequestListener,
LocationFinder.LocationUpdateListener {
private LocationFinder locationUpdater;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationUpdater = new LocationFinder(this, LocationFinder.FinderType.TRACK);
driverLocationUpdater.gpsRequestCallback(this);
driverLocationUpdater.config(5000, 5000);
driverLocationUpdater.find(this);
}
#Override
protected void onDestroy(){
super.onDestroy()
driverLocationUpdater.stopFinder();
}
#Override
public void onLocationUpdate(LatLng latLng) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
LocationFinder.onRequestResult(this, requestCode, resultCode);
}
}

Categories

Resources