Android GPS_PROVIDER always returns null - java

I'm developing an app and when I try to get the location of Android, I always get null.
I try this with a real device, running API 19 and with the GPS enabled
This is my code:
double latitud, longitud;
Location location;
LocationManager mlocManager;
LocationListener locationListener;
String provider;
final boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
return;
}
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = mlocManager.getBestProvider(criteria, true);
Log.i("PROVIDER", provider);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
latitud = location.getLatitude();
longitud = location.getLongitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
mlocManager.requestLocationUpdates(provider, 0, 0,locationListener);
location = mlocManager.getLastKnownLocation(provider);
if (location != null) {
latitud = location.getLatitude();
longitud = location.getLongitude();
Log.i("LATITUD GPS", String.valueOf(latitud));
Log.i("LONGITUD GPS", String.valueOf(longitud));
} else {
Log.e("LOCATION", "null");
}
}
I tried to use LocationManager.GPS_PROVIDER instead of Criteria, but it doesn't work.
Thanks in advance.

Related

How to show location permissions settings

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

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.

get current location lat and lng on map ready

i want to get current location and move camera to current location and then save current location(LatLng) to my database
i get ACCESS_FINE permission
and use following code, but application has stop working
double lat = map.getMyLocation().getLatitude();
double lng = map.getMyLocation().getLongitude();
LatLng cur = new LatLng(lat,lng);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(cur, 17));
android log cat :
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
getMyLocation(), this method is deprecated.
Try this:
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
double latitude = location.getLatitude();
double longitude = location.getLongitude();
getting current location from map.getMyLocation() is not best way to get current location. you can use this class for finding user current location
public class LocationFinder {
private Timer timer;
private LocationManager locationManager;
private LocationResult locationResult;
private boolean gpsEnabled = false;
private boolean networkEnabled = false;
public boolean getLocation(Context context, LocationResult result) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
locationResult = result;
if (locationManager == null)
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gpsEnabled && !networkEnabled)
return false;
if (gpsEnabled)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0F, locationListenerGps);
if (networkEnabled)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0.0F, locationListenerNetwork);
timer = new Timer();
timer.schedule(new GetLastLocation(), 20000L);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gpsEnabled)
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (networkEnabled)
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}

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

GPS Tracker keeps Asking for Location (Android)

I have got a small problem, my GPS Tracker keeps asking for activating Location while i activate it. I analysed and reanalysed my class but can't find my error...
Someboy care to help?
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context context;
Location location;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
double latitude;
double longitude;
private static final long MinDistanceChangeUpdate = 10;
private static final long MinTimeUpdate = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context){
this.context = context;
getLocation();
}
public Location getLocation(){
try{
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isNetworkEnabled && !isGPSEnabled){
}else{
this.canGetLocation = true;
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MinTimeUpdate, MinDistanceChangeUpdate, 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, MinTimeUpdate, MinDistanceChangeUpdate, 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(){
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is Settings! ");
alertDialog.setMessage("GPS is not enable, Wanna enable?");
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("No", 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;
}
}
MainActivity.java
public class MainActivity extends Activity {
Button btnshowLocation;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnshowLocation = (Button)findViewById(R.id.showLocation);
btnshowLocation.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();
Toast.makeText(getApplicationContext(), "Latitude = " + latitude + " Longitude = " + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
}
}
Stracktrace
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
04-26 23:55:51.943 21374-21374/com.example.dell.exampleapplication W/System.err﹕ at android.content.ContextWrapper.getSystemService(ContextWrapper.java:582)
04-26 23:55:51.943 21374-21374/com.example.dell.exampleapplication W/System.err﹕ at com.example.dell.exampleapplication.GPSTracker.getLocation(GPSTracker.java:44)
04-26 23:55:51.943 21374-21374/com.example.dell.exampleapplication W/System.err﹕ at com.example.dell.exampleapplication.GPSTracker.<init>(GPSTracker.java:39)
04-26 23:55:51.943 21374-21374/com.example.dell.exampleapplication W/System.err﹕ at com.example.dell.exampleapplication.MainActivity$1.onClick(MainActivity.java:28)
Edit : Added Stracktrace
Thanks in advance,
Funny to see a snippet of some code I posted a long time ago in an SO answer :-D Location servise GPS Force closed
Many things has happened since then and my recommendation these days is to use https://github.com/mcharmas/Android-ReactiveLocation
Mainly because:
It uses the Fused location (more battery efficient + better accuracy)
Way less boilerplate code
Additional power of RxJava (no need to dive into details about RxJava for simple usage but it has some awesome features)
I added Activity Recognition to the library (so I like to advertise how awesome I think it is)
To get most recent location the only code you need to write is:
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
locationProvider.getLastKnownLocation()
.subscribe(new Action1<Location>() {
#Override
public void call(Location location) {
doSthImportantWithObtainedLocation(location);
}
});
To vaguely answer your question, my suspicion is that perhaps you have GPS turned on but not WiFi location (just guessing though).
If you are determined to use the code you posted, then I would suggest adding various Log outputs to debug the situation. Something like:
public Location getLocation(){
try{
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isNetworkEnabled && !isGPSEnabled){
Log.e("GPSTracker", "!isNetworkEnabled && !isGPSEnabled");
Log.e("GPSTracker", "is network location enabled: " + isNetworkEnabled );
Log.e("GPSTracker", "is GPS location enabled: " + isGPSEnabled);
}else{
this.canGetLocation = true;
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MinTimeUpdate, MinDistanceChangeUpdate, 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, MinTimeUpdate, MinDistanceChangeUpdate, this);
if(locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}catch(Exception e){
Log.e("GPSTracker", "error getting location", e);
e.printStackTrace();
}
return location;
}
Otherwise pose less restrictive constraints on the canGetLocation boolean (as it is really that variable that is causing you problems)
Changing:
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isNetworkEnabled && !isGPSEnabled){
}else{
this.canGetLocation = true;
...
To
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
this.canGetLocation = isNetworkEnabled || isGPSEnabled;
if(!isNetworkEnabled && !isGPSEnabled){
}else{
...

Categories

Resources