How to show location permissions settings - java

How to show the location permission pop up with an allow and a deny button?
I have function that receives the location, but now I need to go to the settings by myself and turn the location on.
I want that when the User opens the fragment, the location pop up gets shown.
This is the code I currently have:
LocationFinder class:
public class LocationFinder extends Service implements LocationListener {
Context context;
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 200 * 10 * 1; // 2 seconds
// Declaring a Location Manager
protected LocationManager locationManager;
public LocationFinder(Context context) {
this.context = context;
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) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("MissingPermission")
public Location getLocation() {
try {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
// Log.e("Network-GPS", "Disable");
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
// Log.e("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
} else
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
//Log.e("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
Fragment that shows location:
public class GarageFragment extends Fragment {
LocationFinder finder;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_garage, container, false);
getLocation();
return view;
}
public void getLocation() {
double longitude = 0.0;
double latitude = 0.0;
finder = new LocationFinder(getContext());
if (finder.canGetLocation()) {
latitude = finder.getLatitude();
longitude = finder.getLongitude();
// Toast.makeText(getActivity(), "lat-lng " + latitude + "--" + longitude, Toast.LENGTH_LONG).show();
} else {
finder.showSettingsAlert();
}
Geocoder gcd = new Geocoder(getContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses.size() > 0) {
Toast.makeText(getActivity(), addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
} else {
// do your stuff
}
}
}

add this code to check your permission
if (ContextCompat.checkSelfPermission(Activity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(SplashActivity.this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS = { ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION};
ActivityCompat.requestPermissions(Activity.this, PERMISSIONS, 600);
} else {
// your code
}
add in your resultActivity
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.v("requestCode", "requestCode=" + requestCode);
switch (requestCode) {
case 600:
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_GRANTED) {
//allowed
} else {
//set to never ask again
ActivityCompat.requestPermissions(SplashActivity.this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 700);
}
break;
case 700:
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_GRANTED) {
//allowed
} else {
//set to never ask again
ActivityCompat.requestPermissions(SplashActivity.this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 700);
}
break;
}
}

Showing Location permission popup and turning location on are two different things.
You still have to go to setting to turn location on (if it's off), while permission is just allowing your app to use the location when it's on.
To get permission you can use this method RunTimePermissions.verifyStoragePermissions(getActivity());
public class RunTimePermissions {
// Storage Permissions variables
private static final int REQUEST_CODE = 6361;
private static String[] PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION,
};
//persmission method.
public static void verifyStoragePermissions(Activity activity) {
// Check if we have read or write permission
int locationPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
if (locationPermission != PackageManager.PERMISSION_GRANTED ) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS,
REQUEST_CODE
);
}
}
}

Add in manifests:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Add in your activity:
public class MainActivity extends AppCompatActivity {
String[] locationPermissions= {"android.permission.ACCESS_COARSE_LOCATION","android.permission.ACCESS_FINE_LOCATION"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this, locationPermissions, 121);
}
}
};
handler.postDelayed(runnable, 1000);
}
}

Related

Have latitude and longitude in a service return 0.0

I am a beginner in Android application development. I will get latitude and longitude from GPSTracker.class every 5 minutes for send to SQLite DB in next step but when I call GPSTracker.class
It's return latitude = 0.0 and longitude = 0.0 too
help me please
This is my code
AppService.class
public class AppService extends Service {
private MyThread thread;
PowerManager.WakeLock wl;
double latitude;
double longitude;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
thread = new MyThread();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!thread.isAlive()) {
thread.start();
}
return START_STICKY;
}
private class MyThread extends Thread {
private static final String tag = "Sevice Demo";
private static final int delay = 300000;
private int roundNumber = 0;
private boolean finishService = false;
#Override
public void run() {
while (true) {
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(
getApplicationContext().POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
wl.release();
GPSTracker gps = new GPSTracker(AppService.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Log.d("dddd",String.valueOf(latitude)+" & "+String.valueOf(longitude));
try {
sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (finishService) {
return;
}
}
}
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stop...", Toast.LENGTH_LONG).show();
if (thread.isAlive()) {
stopService(new Intent(this, AppService.class));
}
super.onDestroy();
}
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location locations;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// get GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// get network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//return TODO;
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
}
if (locationManager != null) {
locations = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (locations != null) {
latitude = locations.getLatitude();
longitude = locations.getLongitude();
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (locations == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
locations = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (locations != null) {
latitude = locations.getLatitude();
longitude = locations.getLongitude();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return locations;
}
public double getLatitude() {
if (locations != null) {
latitude = locations.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (locations != null) {
longitude = locations.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#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) {
}
}
}
The fused location provider is a location API in Google Play services that intelligently combines different signals to provide the location information that your app needs.
The fused location provider manages the underlying location technologies, such as GPS and Wi-Fi, and provides a simple API that you can use to specify the required quality of service. For example, you can request the most accurate data available, or the best accuracy possible with no additional power consumption.
Last Known Location
Receiving Location Updates
This code
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
locations = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (locations != null) {
latitude = locations.getLatitude();
longitude = locations.getLongitude();
}
}
needs to be refactored. When you call LocationManager.requestUpdates() you are asking the LocationManager to call your app back when there is an update to the GPS position. This will happen at some later time (in the future), depending on how long it takes for the phone to determine its position using GPS. The call to LocationManager.getLastKnownLocation() will only return the last "known" location, which it doesn't have yet.
Once you have requested location updates, Your app will be called back with GPS data. The framework will call the method onLocationChanged(). You currently have no code in that method, so you won't do anything when the method is called.

Getting permission on runtime in android

I'm new to android, don't know what I'm doing wrong
this class get longitude and latitude and sent to another class
the code is throwing an error onrequstpermission please tell me what to do how to do:
error on public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Manifest.permission.ACCESS_COARSE_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good!
} else {
Toast.makeText(this, "Need your location!", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
onRequestPermissionsResult is a method which should be outside the current method
public Location getLocation(){
//...code
if (ActivityCompat.checkSelfPermissio... ) {
// ERROR : cannot have function declaration inside another function
public void onRequestPermissionsResult(...) {
switch (requestCode) {//..code}
}
}
Note: you cannot have this in a Service class , you need some Activity to ask permission
ActivityCompat.OnRequestPermissionsResultCallback is implemented by FragmentActivity which is a parent of AppCompatActivity so it's not implemented by Service so you need to implement the runtime-permission code is some FragmentActivity | AppCompatActivity or you can check and show a notification (in case of no permission or probably a dialog) and redirect user to Activity to proceed with permission code.
Reference:
Implement runtime permission

java android studio - check permission

i want to get coordinat and i'm use function GPSTracker (follow tutorial https://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/) but any issue... i can't get coordinates, please help me guys
this is my acitivity :
public class InputDataSlo extends AppCompatActivity {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GPSTracker gps = new GPSTracker (InputDataSlo.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude= gps.getLongitude();
textView.setText("Latitude: "+latitude+" Longitude: "+longitude);
}else{
Toast.makeText(getApplicationContext(),
"Please cek permision", Toast.LENGTH_LONG)
.show();
}
}
});
}
This is file GPSTracker.java :
public class GPSTracker extends Service implements LocationListener {
private Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude, longitude;
LocationManager locationManager;
AlertDialogManager am = new AlertDialogManager();
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
private Location getLocation() {
// TODO Auto-generated method stub
try {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled) {
this.canGetLocation = true;
if (location == null) {
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
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 3, this);
if (locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} else {
showAlertDialog();
}
}catch(Exception e){
e.printStackTrace();
}
return location;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(GPSTracker.this);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.delete);
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
dialog.cancel();
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void showAlertDialog(){
am.showAlertDialog(GPSTracker.this, "GPS Setting", "Gps is not enabled. Do you want to enabled it ?", false);
}
public double getLatitude(){
if (location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if (location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null){
this.location = location;
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
My problem with access permissions row :
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
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 3, this);
if (locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
Don't use GPSTracker. The code is broken- it will sometimes work, but its flawed at a design level. It confuses enabled with up and running, and doesn't account for the fact you can't always get locations. For a full explanation of all the ways its broken, see my blog at http://gabesechansoftware.com/location-tracking/ which also contains working code.
Also, you need runtime permissions (which aren't in my blog either, as it predates them). You'll need to add those in regardless.

Android Location return null after Enabling GPS in dialog

When I enter a screen, I check for if GPS is turned on, if not, the dialog to enable GPS is shown. When user clicks Yes, onActivityResult -> GPS is turned on and I try to get the location but this always returns null
When I enter the screen with GPS already on, location is retrieved properly. I have been struggling with this for few days now and can't seem to find any resources.
UserLocationUtilities.java
public class UserLocationUtilities implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{
GoogleApiClient googleApiClient;
Activity activity;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Location location;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1 * 1000 * 60; // 1 minute
public UserLocationUtilities(Activity activity){
this.activity = activity;
}
public void settingsRequest()
{
if(googleApiClient == null){
googleApiClient = new GoogleApiClient.Builder(activity)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
}
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(activity, 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;
}
}
});
}
public Location getLocation() {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
try {
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return location;
}
public boolean isLocationEnabled() {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(activity.getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}else{
locationProviders = Settings.Secure.getString(activity.getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#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) {
}
}
After user selects Yes in Settings Dialog, onActivityResult, I do location = userlocationutilities.getLocation(); and always returns null. If switch screens and come back, location is retrieved.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK: //location settings dialog, user selected YES to enabling location
location = userLocationUtilities.getLocation();
if(location != null){
//location of user FOUND
Toast.makeText(getActivity(), "Lat: "+location.getLatitude()+" Long: "+location.getLongitude(), Toast.LENGTH_LONG).show();
getRingsNearMeCall();
}else{
//location of user NOT FOUND
Toast.makeText(getActivity(), "null location", Toast.LENGTH_LONG).show();
}
break;
case Activity.RESULT_CANCELED: //location settings dialog, user selected NO to enabling location
userLocationUtilities.settingsRequest(); //ask user again with Location Settings Dialog
break;
}
break;
}
}
Editted: I make the requestPermission in the fragment, the permission is granted
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[] { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION },
PERMISSION_ACCESS_FINE_LOCATION);
}else{
checkLocationSettingsGetRings();
}
LocationSettingsRequest is used just make location settings adequate, for example you want receive more accurate (HIGH_ACCURACY) locations, then you need GPS is enabled. So in that case, LocationSettingsRequest prompts the dialog to allow api change settings.
After pressing OK, you can see that GPS is enabled. But it does not mean you are granted to make location request yet.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
// Here means required settings are adequate.
// We can make location request.
// But are we granted to use request location updates ?
break;
}
break;
}
}
}
Thats okay, but you are checking the permission, but you did never make requestPermissions. This is the first possible reason of getting null.
public Location getLocation() {
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
...
}
return location;
}
Even you are previously granted to make location request
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
getLastKnownLocation() method could return null, this is not unexpected behaviour. This is the second possible reason of getting null
You are making location request, but the global location variable is never assigned in onLocationChanged callback.
#Override
public void onLocationChanged(Location location) {
// global location variable is not assigned ?
// getLocation() method will return null if getLastKnownLocation()
// did not return null previously.
}
This is third possible reason of getting null.
Finally, I find a solution:
I create a thread and wait for my location available.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case REQUEST_LOCATION:
switch (resultCode){
case Activity.RESULT_OK:
mHandler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
mHandler.postDelayed(this,1000);
checkLocationAvailable();
}
};
mHandler.postDelayed(runnable,1000);
break;
case Activity.RESULT_CANCELED:
break;
}
}
}
Create a function to stop the thread when my location available.
private void checkLocationAvailable(){
if (mMap.getMyLocation() != null) {
mHandler.removeCallbacks(runnable);
// do stuff
}
}
It is not a good solution, but hope it will help.
Add this override method for me its worked fine--
#Override
public void onLocationChanged(Location location) {
getLocation("onLocationChanged");
}

Android Wear App java.lang.OutOfMemoryError: Failed to allocate

I had a problem. I want to make an Android App for my Android Wear device. I want to get the latitude and longitude of my current location. But when I run the applicatie I got this error:
03-22 11:14:00.096 29013-29013/? E/AndroidRuntime: Error reporting crash
java.lang.OutOfMemoryError: Failed to allocate a 52435096 byte allocation with 2097152 free bytes and 32MB until OOM
at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:125)
at java.lang.StringBuffer.append(StringBuffer.java:278)
at java.io.StringWriter.write(StringWriter.java:123)
at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:358)
at com.android.internal.util.FastPrintWriter.appendLocked(FastPrintWriter.java:303)
at com.android.internal.util.FastPrintWriter.write(FastPrintWriter.java:625)
at com.android.internal.util.FastPrintWriter.append(FastPrintWriter.java:658)
at java.io.PrintWriter.append(PrintWriter.java:691)
at java.io.PrintWriter.append(PrintWriter.java:687)
at java.io.Writer.append(Writer.java:198)
at java.lang.Throwable.printStackTrace(Throwable.java:324)
at java.lang.Throwable.printStackTrace(Throwable.java:300)
at android.util.Log.getStackTraceString(Log.java:343)
at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:61)
at com.android.internal.os.RuntimeInit.-wrap0(RuntimeInit.java)
at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:86)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
This is my code:
MainActivity.java
public class MainActivity extends Activity {
private TextView tvHuidigeLocatie;
private Button btSetHuidigeLocatie;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
onClickInfoButtonListener();
}
});
}
private void onClickInfoButtonListener() {
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
tvHuidigeLocatie = (TextView) stub.findViewById(R.id.tvHuidigeLocatie);
btSetHuidigeLocatie = (Button) stub.findViewById(R.id.btnSetHuidigeLocatie);
btSetHuidigeLocatie.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
tvHuidigeLocatie.setText("" + latitude + ", " + longitude);
}else{
gps.showSettingsAlert();
}
}
}
);
}
}
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return location;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation();
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS in settings");
alertDialog.setMessage("GPS staat niet aan, Wilt u naar uw instellingen gaan?");
alertDialog.setPositiveButton("Instellingen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Annuleer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#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) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I hope anyone see the problem and can help me with this problem.
android:largeHeap="true"
In your android manifest, hope this will solve your problem.
http://developer.android.com/guide/topics/manifest/application-element.html#largeHeap

Categories

Resources