how to solve turning off Location - java

I have following script to get Location using GoogleAPI. Working on My App is based on Location. When This Activity was opened, thanks to using GoogleAPI is got Location Known as Latitude and Longitude.
When MainActivity is opened, if Location turns on within Device Settings.(Android smart Phone).Location Knowledge is obtained as a successfully way and in MainActivity doesn't happen any Problems. Conversely, when Location Turns off on
my android device, while the Activity is started, I have error and App close with a message that called "Unfortunately The App has stopped".
How can I solve this problem? while The Activity is opening How to Control whether Location turns on or off.
thanks in advance for the whole help.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
, LocationListener , DialogInterface.OnClickListener {
public static final String KEY_LOC_ADD_URL = "http://xxxxxxxx/android_api/insertlocation.php";
public static final String KEY_LATITUDE = "enlem";
public static final String KEY_LONGITUDE = "boylam";
public static final String KEY_ID="id";
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location mevcutKonum;
private String[] seconds={"1","3","5","7","10"};
private String sonGuncellemeZamani;
private String employee_id;
private Long requestTime;
private TextView enlemTextView;
private TextView boylamTextView;
private TextView sonGuncellemeTextView;
private TextView employee_name;
private AlertDialog dialogSelectInternal;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enlemTextView = (TextView) findViewById(R.id.enlem);
boylamTextView = (TextView) findViewById(R.id.boylam);
sonGuncellemeTextView = (TextView) findViewById(R.id.guncellemezamani);
sonGuncellemeZamani = "";
employee_name= (TextView) findViewById(R.id.userName);
Intent intent = getIntent();
employee_name.setText("Welcome User " + intent.getStringExtra(Login_Activity.KEY_USERNAME));
employee_id=intent.getStringExtra(Login_Activity.KEY_ID);
buildGoogleApiClient();
selectRequestTimeDialog();
createLocationRequest();
}
protected void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void createLocationRequest() {
locationRequest = LocationRequest.create()
.setInterval(3000)
.setFastestInterval(1000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void updateUI() {
if (mevcutKonum != null) {
enlemTextView.setText(String.valueOf(mevcutKonum.getLatitude()));
boylamTextView.setText(String.valueOf(mevcutKonum.getLongitude()));
sonGuncellemeTextView.setText(sonGuncellemeZamani);
}
}
#Override
protected void onResume() {
super.onResume();
googleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (googleApiClient.isConnected()) {
stopLocationUpdates();
}
googleApiClient.disconnect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (mevcutKonum == null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mevcutKonum = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
try {
addLocationToUser(String.valueOf(mevcutKonum.getLatitude()),String.valueOf(mevcutKonum.getLongitude()),employee_id);
} catch (JSONException e) {
e.printStackTrace();
}
updateUI();
}
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mevcutKonum = location;
sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void addLocationToUser(final String latitude, final String longitude,final String id) throws JSONException {
StringRequest stringRequest = new StringRequest(Request.Method.POST, KEY_LOC_ADD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(KEY_LATITUDE,latitude);
params.put(KEY_LONGITUDE, longitude);
params.put(KEY_ID,id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void selectRequestTimeDialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Konumunuzu Güncellemek istediğiniz zaman aralığını seçiniz");
builder.setItems(seconds,this);
builder.setNegativeButton("Cancel", null);
dialogSelectInternal=builder.create();
dialogSelectInternal.show();
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
Above Code has worked when location only turns on

In your onCreate() , First check if your GPS is enabled in your device, if yes create location update, else go to Location Settings.
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createLocationRequest();
} else {
Toast.makeText(this, "Please enable your gps first.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent, 1);
}
On GPS -> HIGH ACCURACY selection:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 1) {
switch (requestCode) {
case 1:
createLocationRequest();
break;
}
}
}
Hope this helps.

Related

Mapbox Map not showing on android

When I tested it the first couple of times it was showing perfectly well, then I added some code and it just stopped. It still shows the Mapbox logo on the left bottom screen but it's not loading the map. Here's the code on the MapActivity:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, LocationEngineListener, PermissionsListener {
private MapView mapView;
private Button startButton;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private Location originLocation;
private LocationLayerPlugin locationLayerPlugin;
private Locash customerLocash;
private Point destinationPosition;
private Point originPosition;
private Marker destinationMarker;
private NavigationMapRoute navigationMapRoute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_map);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
startButton = findViewById(R.id.startButton);
Intent activityIntent = getIntent();
String locationJson = activityIntent.getStringExtra("location");
Gson gson = new Gson();
customerLocash = gson.fromJson(locationJson,Locash.class);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Launch Navigation
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.origin(originPosition)
.destination(destinationPosition)
.shouldSimulateRoute(true)
.build();
NavigationLauncher.startNavigation(MapActivity.this, options);
}
});
}
#Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
enableLocation();
LatLng point = new LatLng(customerLocash.getLongitude(),customerLocash.getLatitude());
destinationMarker = map.addMarker(new MarkerOptions().position(point));
destinationPosition = Point.fromLngLat(point.getLongitude(),point.getLatitude());
originPosition = Point.fromLngLat(originLocation.getLongitude(), originLocation.getLatitude());
getRoute(originPosition, destinationPosition);
startButton.setEnabled(true);
}
private void enableLocation() {
if (PermissionsManager.areLocationPermissionsGranted(this)){
initializeLocationEngine();
initializeLocationLayer();
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings("MissingPermission")
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this)
.obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null){
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
#SuppressWarnings("MissingPermission")
private void initializeLocationLayer() {
locationLayerPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationLayerPlugin.setLocationLayerEnabled(true);
locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
}
private void setCameraPosition(Location location){
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),
location.getLongitude()),13.0));
}
private void getRoute(Point origin, Point destination){
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (response.body() == null){
Toast.makeText(MapActivity.this, "No Routes Found", Toast.LENGTH_SHORT).show();
return;
} else if (response.body().routes().size() == 0){
Toast.makeText(MapActivity.this, "No Routes Found", Toast.LENGTH_SHORT).show();
return;
}
DirectionsRoute currentRoute = response.body().routes().get(0);
navigationMapRoute = new NavigationMapRoute(null, mapView,map);
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Toast.makeText(MapActivity.this, "Error:" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#SuppressWarnings("MissingPermission")
#Override
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null){
originLocation = location;
setCameraPosition(location);
}
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, "Location Required", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted){
enableLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
#SuppressWarnings("MissingPermission")
protected void onStart() {
super.onStart();
if (locationEngine != null){
locationEngine.requestLocationUpdates();
}
if (locationLayerPlugin != null){
locationLayerPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null){
locationEngine.removeLocationUpdates();
}
if (locationLayerPlugin != null){
locationLayerPlugin.onStop();
}
mapView.onStop();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (locationEngine != null){
locationEngine.deactivate();
}
mapView.onDestroy();
}
}
Oh and the Locash object is a class I use to store user location on firebase and the likes.
Looks like a problem I had. Not sure if this is the same, but in my case setting the textureView option to true solved it.
This is how I did it in code:
val resourceOptions = ResourceOptions.Builder()
.accessToken(context.getString(R.string.mapbox_access_token))
.build()
mapView = MapView(context, MapInitOptions(context, resourceOptions).apply { textureView = true })
I am not sure how to do it in XML.

Get current user location- Android

I know there are a lot of examples on the internet about this subject but my problem isn't the code, is the part where I get the location. The FusedLocationProviderClient.getLastLocation() always returns null when I don't open Google Maps before. To get my current location I have to open google maps to get my current location and after that my app can know the location. My question is: is there a way to track my current location without opening google maps before? Here is what I tried:
package com.example.gps;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final int DEFAULT_UPDATE_INTERVAL = 30;
public static final int FAST_UPDATE_INTERVAL = 5;
public static final int PERMISSIONS_FINE_LOCATION = 99;
TextView tv_lat, tv_lon, tv_altitude,
tv_accuracy, tv_speed, tv_sensor, tv_updates, tv_address;
Switch sw_locationupdates, sw_gps;
// Google API for location services.
FusedLocationProviderClient fusedLocationProviderClient;
// Location request config file for all settings related to FusedLocationProviderClient
LocationRequest locationRequest;
LocationCallback locationCallBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_lat = findViewById(R.id.tv_lat);
tv_lon = findViewById(R.id.tv_lon);
tv_altitude = findViewById(R.id.tv_altitude);
tv_accuracy = findViewById(R.id.tv_accuracy);
tv_speed = findViewById(R.id.tv_speed);
tv_sensor = findViewById(R.id.tv_sensor);
tv_updates = findViewById(R.id.tv_updates);
tv_address = findViewById(R.id.tv_address);
sw_gps = findViewById(R.id.sw_gps);
sw_locationupdates = findViewById(R.id.sw_locationsupdates);
locationRequest = new LocationRequest();
locationRequest.setInterval(1000 * DEFAULT_UPDATE_INTERVAL);
locationRequest.setFastestInterval(1000 * FAST_UPDATE_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationCallBack = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
updateUIValues(locationResult.getLastLocation());
}
};
sw_locationupdates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sw_locationupdates.isChecked()) {
startLocationUpdates();
} else {
stopLocationUpdates();
}
}
});
sw_gps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sw_gps.isChecked()) {
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
String text = "Using GPS sensors";
tv_sensor.setText(text);
} else {
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
String text = "Using Towers + WIFi";
tv_sensor.setText(text);
}
}
});
updateGPS();
}// end onCreate
private void stopLocationUpdates() {
String text = "Location is NOT being tracked";
tv_updates.setText(text);
Toast.makeText(this, "done", Toast.LENGTH_SHORT).show();
fusedLocationProviderClient.removeLocationUpdates(locationCallBack);
}
private void startLocationUpdates() {
String text = "Location is being tracked";
tv_updates.setText(text);
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, "a", Toast.LENGTH_SHORT).show();
// 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.
// requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
// Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_FINE_LOCATION);
// return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallBack, null);
updateGPS();
Toast.makeText(this, "tracking again", Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSIONS_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
updateGPS();
} else {
Toast.makeText(this, "This app requires permission to be granted in order to work properly", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void updateGPS() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
updateUIValues(location);
}
});
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSIONS_FINE_LOCATION);
}
}
}
private void updateUIValues(Location location) {
if (location != null) {
tv_lat.setText(String.valueOf(location.getLatitude()));
tv_lon.setText(String.valueOf(location.getLongitude()));
tv_accuracy.setText(String.valueOf(location.getAccuracy()));
if (location.hasAltitude()) {
tv_altitude.setText(String.valueOf(location.getAltitude()));
} else {
String text = "Not available- altitude";
tv_altitude.setText(text);
}
if (location.hasSpeed()) {
tv_speed.setText(String.valueOf(location.getSpeed()));
} else {
String text = "Not available- speed";
tv_speed.setText(text);
}
Geocoder geocoder = new Geocoder(MainActivity.this);
try {
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
tv_address.setText(addressList.get(0).getAddressLine(0));
} catch (IOException e) {
String text = "geocode didnt work";
tv_address.setText(text);
e.printStackTrace();
}
} else {
Toast.makeText(this, "the gps doesnt work", Toast.LENGTH_SHORT).show();
}
}
}
This code will retrieve my current location and update the name of the location but it will only work if I open google maps, close google maps and launch my app, it will work. Maybe this is the only way to make it work? But I wonder how other apps can track my location without opening google maps before.
yes, you can do it using its fused location provider also...without a map...
These code work without map I Hope You have apply runtime permission code
also apply for permission in the android manifest check it...
follow these URL - https://javapapers.com/android/android-location-fused-provider/
public class HomeFragment extends Fragment implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient googleApiClient;
LocationRequest locationRequest;
Location mCurrentLocation;
private static final long INTERVAL = 1000;
private static final long FASTEST_INTERVAL = 1000;
private int Play_SERVICES_RESOLUTION_REQUEST = 11;
FragmentHomeBinding binding;
AddressListDialogBinding dialogBinding;
AddressInterface anInterface;
FirebaseFirestore firebaseFirestore;
BottomSheetDialog dialog;
public HomeFragment() {
}
protected void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
LayoutInflater layoutInflater = getLayoutInflater();
binding = FragmentHomeBinding.inflate(layoutInflater);
View view = binding.getRoot();
setHasOptionsMenu(true);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
if (!isGooglePlayServicesAvailable()) {
}
createLocationRequest();
anInterface = this;
// setAddress();
googleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
public void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
googleApiClient.disconnect();
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
return false;
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
Log.d("LocationUpdate", "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(#NonNull int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
updateUI();
}
private void updateUI() {
if (mCurrentLocation != null) {
Log.e("getLocation", "updateUI: " + mCurrentLocation.getLatitude() + ":" + mCurrentLocation.getLongitude());
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(), 1);
String address = addresses.get(0).getAddressLine(0);
binding.tvCurrentLocation.setText(address);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onPause() {
super.onPause();
stopLocationUpdate();
}
protected void stopLocationUpdate() {
try {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
} catch (Exception e) {
Log.e("error", "stopLocationUpdate: " + e.toString());
}
}
#Override
public void onResume() {
super.onResume();
if (googleApiClient.isConnected()) {
startLocationUpdates();
}
}
}

need to check if gps is enabled or not

i am making a app in which on click of button it moves from 1 activity to 2nd activity on which i need gps to be active i used a alertdialog box to turn on the gps by clicking settings it will open to the setting and if i enable it dialogbox disapper and gps start working but if i press back button without enabling the gps it works and activity starts i want to check if gps is enabled if not the it should not show me the 2nd activity
No Error Coming but just on back press on setting without enabling it will start activity without any error and still gps is off.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
textView1 = (TextView) findViewById(R.id.location_view);
button1 = (Button) findViewById(R.id.camera);
button2 = (Button) findViewById(R.id.upload);
editText1 = (EditText) findViewById(R.id.remarks);
imageView11 = (ImageView) findViewById(R.id.image1);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
locationText = (TextView) findViewById(R.id.location_view);
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat
.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission
.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, (LocationListener) this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.item1:
Toast.makeText(getApplicationContext(),"Account Clicked",Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Account Clicked",Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Confirm Logout");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("Are You Sure You Want to Logout ");
alerDialogbuilder.setMessage("Logingout will need id password again");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intents = new Intent(Main3Activity.this,MainActivity.class);
startActivity(intents);
Toast.makeText(getApplicationContext(),"Successfull Logout",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Logout Canceled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
return true;
default:return super.onOptionsItemSelected(item);
}
}
private void camera(){
Intent intents = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intents,CAMERA_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==CAMERA_REQUEST&&resultCode== Activity.RESULT_OK){
Bitmap photo= (Bitmap)data.getExtras().get("data");
imageView11.setImageBitmap(photo);
}
}
private void upload(){
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Confirm Upload ?");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("Are You Sure You Want to Upload Data");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"File Uploading...",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Recheck Data",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
}
#Override
public void onClick(View view) {
if(view==button1){
camera();
}
else if (view == button2){
upload();
}
}
#Override
public void onLocationChanged(Location location) {
double lati = location.getLatitude();
double longi = location.getLongitude();
locationText.setText("Latitude: " + lati + "\n Longitude: " + longi);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Toast.makeText(this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Enable Gps to Continue");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("If You Want To Enable Gps Go To Settings");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent1);
Toast.makeText(getApplicationContext(),"Enable Gps..",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
Toast.makeText(getApplicationContext(),"Uploading Failed,Enable Gps",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
}
}
i want to check only if gps is enabled or not when my activity start if it is not enabled go to settings and still if the user doesnot enable the gps setting it should not work any further pls help me out m a new to android
Implement below method for checking status -:
public boolean CheckGpsStatus() {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return GpsStatus;
}
protected LocationRequest locationRequest;
public void checkForLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setInterval(MIN_UPDATE_INTERVAL);
locationRequest.setNumUpdates(1);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
public void checkForLocationSettings() {
try {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(MainActivity.this);
settingsClient.checkLocationSettings(builder.build())
.addOnSuccessListener((Activity) MainActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// delay(1);
//Setting is success...
// Toast.makeText(SplashActivity.this, "Enabled the Location successfully. Now you can press the buttons..", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener((Activity) MainActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult((Activity) MainActivity.this, GET_PERMISSION_REQ_CODE);
} catch (Exception ex) {
new MyUtils().catchError(MainActivity.this, ex);
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Toast.makeText(MainActivity.this, "Setting change is not available.Try in another device.", Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
new MyUtils().catchError(MainActivity.this, e);
}
}
This Above code shows the popup for enable the gps if gps is not enabled and also gives you callback for success and failure
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,OnMapReadyCallback,LocationListener{
protected static final String TAG = "MainActivity";
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
Marker mCurrLocationMarker;
GoogleMap mgooglemap;
private LocationManager locationManager;
#Override
public void onLocationChanged(Location location) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// MarkerOptions markerOptions = new MarkerOptions();
// markerOptions.position(latLng);
// markerOptions.title("Current Position");
// markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// mCurrLocationMarker = mgooglemap.addMarker(markerOptions);
//move map camera
mgooglemap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
mgooglemap.getMaxZoomLevel();
// locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Please Enable GPS", Toast.LENGTH_LONG).show();
//for you want to open Settings screen
while(!onProviderEnabled())
{
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
}
The onProviderDisabled() of the above code will provide you the required flow.

How to track friends location?

I am new in this field and I am trying to make application to track my friends like "snap-map". I am able to get my real-time location but I don't know what should I add to get real-time location of people who are using same application.
Here is my Java code, it will really helpful for me if you guys give me a code.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private FirebaseAuth mAuth;
final static int PERMISSION_ALL = 1;
final static String[] PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
private GoogleMap mMap;
MarkerOptions mo;
Marker marker;
private Location user;
LocationManager locationManager;
private HashMap<Float, Location> otherUser = new HashMap<Float, Location>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mAuth = FirebaseAuth.getInstance();
// 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);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mo = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location");
if (Build.VERSION.SDK_INT >= 27 && !isPermissionGranted()) {
requestPermissions(PERMISSIONS, PERMISSION_ALL);
} else requestLocation();
if (!isLocationEnabled())
showAlert(1);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
marker = mMap.addMarker(mo);
}
//Called when the location has changed.
#Override
public void onLocationChanged(Location location) {
LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
marker.setPosition(myCoordinates);
mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates));
}
//Called when the provider status changes.
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
//Called when the provider is enabled by the user.
#Override
public void onProviderEnabled(String provider) {
}
//Called when the provider is disabled by the user. If requestLocationUpdates
#Override
public void onProviderDisabled(String provider) {
}
private void requestLocation() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
String provider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(provider, 10000, 10, this);
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean isPermissionGranted() {
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Log.v("mylog","Permission is granted");
return true;
}else{
Log.v("mylog","Permission not granted");
return false;
}
}
private void showAlert(final int status) {
String message, title, btnText;
if (status == 1) {
message = "Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app";
title = "Enable Location";
btnText = "Location Settings";
} else {
message = "Please allow this app to access location!";
title = "Permission access";
btnText = "Grant";
}
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setCancelable(false);
dialog.setTitle(title)
.setMessage(message)
.setPositiveButton(btnText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
if (status == 1) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
} else
requestPermissions(PERMISSIONS, PERMISSION_ALL);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}

Cannot run android app in background through service

I try to get current location when the app running in background, so I use service. However, the data does not change in background, the service does not work. I want to know the problem. Here is the code of the app.
MainActivity as follow:
public class MainActivity extends Activity {
Button btn_start;
private static final int REQUEST_PERMISSIONS = 100;
boolean boolean_permission;
TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality;
SharedPreferences mPref;
SharedPreferences.Editor medit;
Double latitude,longitude;
Geocoder geocoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
tv_address = (TextView) findViewById(R.id.tv_address);
tv_latitude = (TextView) findViewById(R.id.tv_latitude);
tv_longitude = (TextView) findViewById(R.id.tv_longitude);
tv_area = (TextView)findViewById(R.id.tv_area);
tv_locality = (TextView)findViewById(R.id.tv_locality);
geocoder = new Geocoder(this, Locale.getDefault());
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
medit = mPref.edit();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolean_permission) {
if (mPref.getString("service", "").matches("")) {
medit.putString("service", "service").commit();
Intent intent = new Intent(getApplicationContext(), GoogleService.class);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
});
fn_permission();
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = Double.valueOf(intent.getStringExtra("latitude"));
longitude = Double.valueOf(intent.getStringExtra("longitude"));
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
tv_area.setText(addresses.get(0).getAdminArea());
tv_locality.setText(stateName);
tv_address.setText(countryName);
} catch (IOException e1) {
e1.printStackTrace();
}
tv_latitude.setText(latitude+"");
tv_longitude.setText(longitude+"");
tv_address.getText();
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Service as follow:
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver =
"com.findmyelderly.findmyelderly.receiver";
Intent intent;
public GoogleService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
intent = new Intent(str_receiver);
// fn_getlocation();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable) {
} else {
if (isNetworkEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
if (isGPSEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
}
private class TimerTaskToGetLocation extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
fn_getlocation();
}
});
}
}
private void fn_update(Location location){
intent.putExtra("latutide",location.getLatitude()+"");
intent.putExtra("longitude",location.getLongitude()+"");
sendBroadcast(intent);
}
}
build.gradle as follow
.........
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.android.support:multidex:1.0.0'
AndroidManifest as follow
..........
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
.........
<service android:name=".GoogleService" android:exported="false" android:enabled="true"/>
</application>
</manifest>
I am very puzzled.
One thing you could try is to check the permissions of the app on the phone itself. I've found with my device (Android version 6.0.1) it's not enough to just add "uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> and
"uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />"
in the manifest, you have to grant permissions to the app manually on the device.
To do this, go to Settings > Apps > 'yourApp' > Permissions and slide across the bar to turn on Location for that app.
I'm new enough to Android apps myself so there may be a bigger problem in your case I'm not sure but worth a try anyway!

Categories