I am creating an Android application to get my current GPS location. First it was working, but now it always returns null. It just shows the GPS icon in my phone's notification bar but the icon is not getting activated or highlighted. I tried many tricks but nothing have worked so far. Here is my code:
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@SuppressLint("RestrictedApi")
@Override
public void onClick(View view) {
fab.setVisibility(View.VISIBLE);
GpsTracker gt = new GpsTracker(getApplicationContext());
Location l = gt.getLocation();
if(l != null) {
double lat = l.getLatitude();
double lon = l.getLongitude();
Toast.makeText(getApplicationContext(),"GPS Lat = "+lat+"\n lon = "+lon,Toast.LENGTH_SHORT).show();
Snackbar.make(view, "GPS Lat = "+lat+"\n lon = "+lon, Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else {
Snackbar.make(view, "GPS unable to Connect", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
Toast.makeText(getApplicationContext(),"GPS unable to Connect",Toast.LENGTH_SHORT).show();
}
}
});
GpsTracker.java
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import static android.content.Context.LOCATION_SERVICE;
public class GpsTracker implements LocationListener {
public Context context;
public GpsTracker(Context context) {
super();
this.context = context;
}
public Location getLocation(){
if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
Log.e("fist","error");
return null;
}
try {
LocationManager lm = (LocationManager) context.getSystemService(LOCATION_SERVICE);
boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000,10,this);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return loc;
} else {
Log.e("sec","Please enable your GPS");
}
} catch (Exception e) {
e.printStackTrace();
}
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) {
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />