i have MainActivty and MyLocationListener classes.
MyLocationListener extends AsyncTask implements LocationListener..
Here is code of the Location Listener Class:
private class MyLocationListener extends AsyncTask implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// convert coords from double to string
String lat = Double.toString(location.getLatitude());
String lon = Double.toString(location.getLongitude());
Log.i(AppHelper.APP_LOG_NAMESPACE, "lat " + lat);
Log.i(AppHelper.APP_LOG_NAMESPACE, "lon " + lon);
// save actual position into shared preferences storage
_appPrefs = new AppPreferences(activityContext);
_appPrefs.saveSomeString("lat", lat);
_appPrefs.saveSomeString("lon", lon);
getAddressByCoords(location.getLatitude(),
location.getLongitude());
setPositionToView(activityContext, mView);
}
/**
* Method get string representation of the place in given coords
*
* #param lat
* double
* #param lon
* double
* #return List <Address>
* #throws Exception
*/
public List<Address> getAddressByCoords(double lat, double lon) {
Geocoder gCoder = new Geocoder(activityContext);
try {
addresses = gCoder.getFromLocation(lat, lon, 1);
if (addresses != null && addresses.size() > 0) {
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(0));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(1));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(2));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return addresses;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this,
provider + "'s status changed to " + status + "!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " enabled!", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " disabled!", Toast.LENGTH_SHORT)
.show();
}
#Override
protected Object doInBackground(Object... params) {
try {
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // default
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager
.getLastKnownLocation(provider);
// request single update
this.onLocationChanged(location);
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE,
"doInBackground method cannot be processed", e);
e.printStackTrace();
}
return null;
}
}
If i'm trying to get GPS coords using the:
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mView = view;
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// get values from user settings
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
Boolean prefferNativeGPs = sharedPrefs.getBoolean(
"prefNativeGps", false);
Log.i("APP", "GPS enabled " + isGPSEnabled); // false
Log.i("APP", "NETWORK enabled " + isNetworkEnabled); // true
Log.i("APP", "USE native " + prefferNativeGPs); // true
// blink textview
TextView stateTv = (TextView) findViewById(R.id.state);
stateTv.setTextColor(getResources().getColor(R.color.black));
startBlinkText();
Log.i("APP", "GPS POSITION USING GPS_PROVIDER");
Toast.makeText(this,R.string.parking_car_using_gps_it_can_take_more_time,
Toast.LENGTH_LONG).show();
// calling doInBackground
new MyLocationListener().execute("");
I got following exception in doInBackground:
cannot create handler inside thread that has not called looper.prepare
I would like to ask, how to modify my code to do processing correctly?
Many thanks for any help.
Create the handler in the AsyncTask's constructor. You must make it on a thread with an active message loop, like the UI thread.
Getting the location is already an async operation...
All you need to do is to call it on the UI thread, and expect new results soon afterwards (depends on many things).
That's why it has a listener. Otherwise it would just return you a response while blocking you...
Related
For my app, I need to get the location of the user, to fetch corresponding data from a server. The problem is that the code I use doesn't properly return the location when it's opened the first time. After restarting the app once it works just fine. I searched the other questions and found out, that if you use getLastKnownLocation and there is no location since the last reboot, it returns null. But why does it work when the app is restarted? Does it fetch it when it's opened the first time, and how can I make it wait until the location is fetched properly at the first opening then?
The code of my MainActivity:
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
} else {
progressBar.setVisibility(View.VISIBLE);
GPSClass gt = new GPSClass(getActivity().getApplicationContext());
Location location = gt.getLocation();
if (location == null) {
//Toast
} else {
lat = location.getLatitude();
lon = location.getLongitude();
}
new GetContacts().execute();
}
And the GPSClass:
public class GPSClass implements LocationListener {
Context context;
public GPSClass(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, 5000,10,this);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return loc;
}else{
Log.e("sec","error");
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
Here is the full tutorial
I shared a tutorial link follow that link.
Call this below method. It will return value; when lat and long is found. Until object is null or doesn't return any value your app must be idle or show some progress value or tell the user to wait.
InitGeoLocationUpdate.locationInit(SplashScreen.this,
object -> {
double latitude = object.latitude;
double longitude = object.longitude;
Lg.INSTANCE.d(TAG, "Current Location Latitude: " + latitude + " Longitude: " +
longitude);
});
Try this this will not give you null current location
class GetLastLocation extends TimerTask {
LocationManager mlocManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListenerTmp = new CustomLocationListener();
private final Handler mLocHandler;
public GetLastLocation(Handler mLocHandler) {
this.mLocHandler = mLocHandler;
}
#Override
public void run() {
timer.cancel();
mlocManager.removeUpdates(mlocListenerTmp);
Location location = mlocManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
{
if (mlocListenerTmp != null) {
mlocManager.removeUpdates(mlocListenerTmp);
}
currentLocation = location;
}
if (location != null) {
String message = String.format(
"Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Log.d("loc", " :" + message);
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Log.d(
"loc",
":No GPS or network signal please fill the location manually!");
location = mlocManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
currentLocation = location;
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", false);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
}
}
}
}
call it like this in your MainActivity
timer.schedule(new GetLastLocation(mLocHandler), 3000);
and the customLocationclass is as follows:
public class CustomLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
currentLocation = loc;
String Text = "My current location is: " + "Latitud = "
+ loc.getLatitude() + "Longitud = " + loc.getLongitude();
Log.d("loc", "onLocationChanged" + Text);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
I have google searched this with no success and seams very strange to me.
I am building a simple GPS app that send co-ordinates with HttpRequest, though I have noticed when minimising the UI then maximising, It runs a duplicate of the same activity. and doubles up on HttpRequest's
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
processExtraData();
}
private void processExtraData() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10000, 5, this);
}
#Override
public void onLocationChanged(Location location) {
Bundle extras = getIntent().getExtras();
String driver_id = extras.getString("driverid");
String msg = "Driver:" + driver_id + "\nCurrent Location:\nLatitude: " + location.getLatitude()
+ "\nLongitude: " + location.getLongitude();
new HttpRequestTask(
new HttpRequest("https://www.autoflora.net/driver/gps.php?user_id=" + driver_id + "&latlong=" + location.getLatitude() + "*" + location.getLongitude(), HttpRequest.POST, "{ \"some\": \"data\" }"),
new HttpRequest.Handler() {
#Override
public void response(HttpResponse response) {
if (response.code == 200) {
Log.d(this.getClass().toString(), "Request successful!");
} else {
Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
}
}
}).execute();
String s = calc.getText().toString();
calc.setText(s + "1")
TextView driver = (TextView) findViewById(R.id.driver);
driver.setText("" + driver_id);
TextView Longitude = (TextView) findViewById(R.id.longitude);
// Getting reference to TextView tv_latitude
TextView Latitude = (TextView) findViewById(R.id.latitude);
// Setting Current Longitude
Longitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
Latitude.setText("Latitude:" + location.getLatitude());
// Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
noticed when minimising the UI then maximising
There's neither minimising nor maximizing of UI on Android. You apparently start the activity again via launcher (this is most likely your maximizing thing) which creates new instance of you activity. If you want just single instance allowed no matter what, you must set system so by using android:launchMode in declaration of activity in your manifest file. See docs here for possible options.
#Override
public void onStart() {
super.onStart();
Toast.makeText(getBaseContext(), "start", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(this);
}
#Override
public void onResume() {
super.onResume();
Toast.makeText(getBaseContext(), "resume", Toast.LENGTH_LONG).show();
locationcheck(); // checks permissions
}
#Override
public void onPause() {
super.onPause();
Toast.makeText(getBaseContext(), "pause", Toast.LENGTH_LONG).show();
}
#Override
public void onStop() {
super.onStop();
// locationManager.removeUpdates(this);
Toast.makeText(getBaseContext(), "stop", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getBaseContext(), "destroy", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(this);
finish();
}
Seems to have fixed it..
Yesterdy my App worked perfectly but this morning it began to crash. I think the trigger was that I rebooted my Smartphone , so my APP loosed the GPS datas. I started the Debug mode and looked step by step for NULL values and I actuelly find it by this command :
myLocation = locationManager.getLastKnownLocation(provider);
This returns a NULL object which cause to an crash when I try to use these methods :
latitude = myLocation.getLatitude();
longtitude = myLocation.getLongitude();
How can I make that my Location is not NULL in this case ? I tried to use the NETWORK_PROVIDER but then I have to use the WLAN and this is not the best way I think.Can I still catch informations with the GPS_PROVIDER without to get into a other Application which save them ?
BTW here is my Code :
public class gmapps extends FragmentActivity {
private GoogleMap googleMap;
TextView txt_street , txt_city , txt_country ;
Geocoder geocoder;
List<Address> addresses;
ImageView btn_yes;
Location myLocation;
String address , city , country;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
txt_street = (TextView)findViewById(R.id.txt_coordinates);
txt_city = (TextView)findViewById(R.id.txt_city);
txt_country = (TextView)findViewById(R.id.txt_country);
btn_yes = (ImageView)findViewById(R.id.btn_yes);
setUpIfNeeded();
}
private void setUpIfNeeded() {
if (googleMap == null)
{
try{
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
}catch(Exception e){}
if (googleMap != null)
{
setUpMap();
}
}
}
private void setUpMap() {
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria , true);
myLocation = locationManager.getLastKnownLocation(provider); // Here I get the NULL
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
double latitude = myLocation.getLatitude();
double longtitude = myLocation.getLongitude();
LatLng latLng = new LatLng(latitude , longtitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
try {
convert_adresses(latitude,longtitude);
} catch (IOException e) {
e.printStackTrace();
}
txt_street.setText(address);
txt_city.setText(city);
txt_country.setText(country);
}
public void convert_adresses (double lat , double lng) throws IOException
{
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(lat, lng, 1);
address = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getAddressLine(1);
country = addresses.get(0).getAddressLine(2);
}
Thanks everyone !
First you should be using the "new" LocationClent class (which is already depreciated in favor of LocationServices).
https://developer.android.com/reference/com/google/android/gms/location/LocationClient.html
Using this classes getLastLocation(), generally does a good job, but as the documentation says (see below), it can return null at times, so you must check for that.
What you should also do is make a request for location updates (see the doc referenced above), then when the device location becomes available it will call onLocationChanged(Location location) on your listener and you can then do whatever you need to do with the location that is provided.
public Location getLastLocation ()
Returns the best most recent location currently available.
If a location is not available, which should happen very rarely, null will be returned. The best accuracy available while respecting the location permissions will be returned.
This method provides a simplified way to get location. It is particularly well suited for applications that do not require an accurate location and that do not want to maintain extra logic for location updates.
Here is stripped down example of using the location client.
public class DeviceLocationClient implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private Context context;
private LocationClient locationClient;
private boolean isConnected;
private LocationRequest request;
#Override
public void onLocationChanged(Location location) {
System.out.println("got a location update");
if (location != null ) {
// do something with the location
}
}
public DeviceLocationClient(Context context) {
this.context = context;
System.out.println("connecting to google play services");
locationClient = new LocationClient(context, this, this);
isConnected = false;
locationClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
System.out.println("connection to google play services FAILED!");
}
#Override
public void onConnected(Bundle connectionHint) {
System.out.println("google play servies connected");
isConnected = true;
// locationClient.requestLocationUpdates(request, this);
request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setExpirationDuration(60 * 1000);
request.setFastestInterval(5 * 1000);
request.setInterval(10 * 1000);
isConnected = true;
requestLLocationUpdates();
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
System.out
.println("google play services got disconnected - reconnecting");
mBus.unregister(this);
locationClient.connect();
}
#Subscribe
public void onUpdateLocationRequest(UpdateLocationRequest event) {
System.out.println("got the location request");
request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setExpirationDuration(60 * 1000);
request.setFastestInterval(5 * 1000);
request.setInterval(10 * 1000);
locationClient.removeLocationUpdates(this);
locationClient.requestLocationUpdates(request, this);
}
public void requestLLocationUpdates() {
System.out.println("requesting location updates updates");
if (isConnected) {
System.out.println("processing request");
System.out.println("sending latest location");
Location lastLocation = locationClient.getLastLocation();
if (lastLocation != null) {
// do something with the last location
}
request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setExpirationDuration(60 * 1000);
request.setFastestInterval(5 * 1000);
request.setInterval(10 * 1000);
System.out.println("requesting updates");
locationClient.removeLocationUpdates(this);
locationClient.requestLocationUpdates(request, this);
} else {
if (locationClient.isConnecting()) {
System.out.println("google play services is connecting");
} else {
System.out
.println("attempting to connect to google play services");
locationClient.connect();
}
}
}
}
you can put a check for null pointer like this
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Log.d("FlagLocation", "true");
if (provider != null && !provider.equals("")) {
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if (location != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
double kmInLongitudeDegree = 111.320 * Math.cos(lat / 180.0
* Math.PI);
double deltaLat = RADIUS / 111.1;
double deltaLong = RADIUS / kmInLongitudeDegree;
double minLat = lat - deltaLat;
double maxLat = lat + deltaLat;
double minLong = lng - deltaLong;
double maxLong = lng + deltaLong;
}
Just retrieve the location from GPS provider when getLastLocation() == null.
Take a look at the android documentation that does exactly what you need.
http://developer.android.com/training/location/retrieve-current.html
Let me know if you need some example code and I'll edit my answer.
Hope this helps.
Hi i have implemented a Location listener to retrieve the current city name. The only problem that i am having is that i am not too sure what is the best way to return the result to the calling class (MainActivity.java).
This is are some excerpt of my code:
Main Activity
public class MainActivity extends FragmentActivity {
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
flag = displayGpsStatus();
if (flag) {
locationListener = new MyLocationListener(getApplicationContext());
locationManager.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,locationListener);
}else{
Log.i("DEBUG", "UNABLE TO RETRIEVE LOCATION");
}
String lang = "en";
findViewById();
}
and this is my LocationListener class (on separated java file)
public class MyLocationListener implements LocationListener {
private Context mContext;
private String mLocality;
private String mCountry;
public MyLocationListener(Context context){
mContext = context;
}
#Override
public void onLocationChanged(Location location) {
//You had this as int. It is advised to have Lat/Loing as double.
double lat = location.getLatitude();
double lng = location.getLongitude();
String countryName = null;
String subAdmin = null;
String adminArea = null;
String locality = null;
String sublocality = null;
String longitude = "Longitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
Log.i("DEBUG", longitude);
Log.i("DEBUG", latitude);
Geocoder geoCoder = new Geocoder(mContext, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
if(address.size() > 0){
adminArea = address.get(0).getAdminArea().toString();
countryName = address.get(0).getCountryName().toString();
subAdmin = address.get(0).getSubAdminArea();
locality = address.get(0).getLocality();
sublocality = address.get(0).getSubLocality();
}
Log.i("DEBUG", adminArea);
Log.i("DEBUG", countryName);
mLocality = adminArea;
mCountry = countryName;
} catch (IOException e) {}
catch (NullPointerException e) {}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.i("DEBUG", "Disabled provider " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i("DEBUG", "Enabled new provider " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
what i am trying to achieve is to have the city name displayed when the app started and when ever the location is changed.
Should i call onLocationChange() or else?
Can anyone point me to the right direction? Thx for the help.
Extract everything in the onLocationChanged to a method (or a class and put that method in it). Call that method on startup and from the onLocationChanged
i have a problem. When i test this. and i ask for the showCurrentLocation function it always returns null. It works in the emulator when i send the location after. But i need this to work on the phone, and there you can't send the location like in de DDNS window.
Here's my code
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
protected Button stopLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
/*stopLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//locationManager.removeUpdates(MyLocationListener) ;
}
}); */
}
public String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
protected void showCurrentLocation() {
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(crit, true);
Location loc = locationManager.getLastKnownLocation(provider);
if (loc != null) {
String longi = "" + loc.getLongitude();
String lat = "" + loc.getLatitude();
String num = getMyPhoneNumber();
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s ",
longi,
lat,
num );
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}
if (loc == null)Toast.makeText(LbsGeocodingActivity.this, "Null ",
Toast.LENGTH_LONG).show();
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
String longi = "" + loc.getLongitude();
String lat = "" + loc.getLatitude();
String num = getMyPhoneNumber();
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s ",
longi,
lat,
num );
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
My permissions are: FINE_LOCATION COURSE_LOCATION.
I really just want it that it tracks the users location, even on the background..
You can sent mock locations also to your Android device see
Android mock location on device?
Then besides that I had this problem too it seems it maybe never had a location before on your device try to open google maps and make sure you get located and then try again. Also I suspected something like first time you use the application you don't have access to a last know location yet because you never used it so you first need to get located and next time you startup the application it will work. If you want a quick location try to get located by wifi or cell towers
And make sure the permissions are set!
did you checked the GPS is switched on in your phone, after switching on GPS it will take some time to get the location updates.