Android requestLocationUpdates doesn't call never to onLocationChanged in some terminals - java

I'm working on an app that uses the network location, but i've recived some users feedback that says that they never pass this block of code, i'm assuming that the problem is that location changed is never called, but it only happens in a few diveces, and i cant force the failure in mine.
Is there any chance to solve it or control it? showing a toast saying that is unable to find location, will work for me...
I know that if the user reboot his phone, the location will work, but that it's not a solution for the users
I left the code right here...
final LocationManager lm = (LocationManager) thisOfActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// SOME STUFF
Location net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
final LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
lm.removeUpdates(this);
// SOME STUFF
myTask task = new myTask();
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
public void onProviderDisabled(String provider) {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(
thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
Log.e("LocProv", "AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocProv", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.e("LocProv", "TEMPORARILY_UNAVAILABLE");
break;
}
}
};
if (network_enabled) {
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
} else {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_LONG).show();
}
I've tried with the next idea, i think it could work, at least to get a location and not keep the user waiting.
final LocationManager lm = (LocationManager) thisOfActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// SOME STUFF
LocationListener locationListenerNetwork = null;
// Constructor
class MyThread implements Runnable {
LocationListener locationListenerNetwork;
public MyThread(LocationListener lln) {
locationListenerNetwork = lln;
}
public void run() {
}
}
final Handler myHandler = new Handler();
//Here's a runnable/handler combo
final Runnable MyRunnable = new MyThread(locationListenerNetwork)
{
#Override
public void run() {
if (locationListenerNetwork != null)
lm.removeUpdates(locationListenerNetwork);
Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null)
{
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
ListView tweetList = (ListView) thisOfActivity
.findViewById(R.id.tweets);
jsonUpdateAsyncTask task = new jsonUpdateAsyncTask(
thisOfActivity, Double.toString(lat),
Double.toString(lon), tweetList);
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
else
{
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_LONG).show();
}
}
};
locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
lm.removeUpdates(this);
myHandler.removeCallbacks(MyRunnable);
ListView tweetList = (ListView) thisOfActivity
.findViewById(R.id.tweets);
jsonUpdateAsyncTask task = new jsonUpdateAsyncTask(
thisOfActivity, Double.toString(lat),
Double.toString(lon), tweetList);
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
public void onProviderDisabled(String provider) {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(
thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
Log.e("LocProv", "AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocProv", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.e("LocProv", "TEMPORARILY_UNAVAILABLE");
break;
}
}
};
if (network_enabled) {
myHandler.postDelayed(MyRunnable, 10 * 1000);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0,locationListenerNetwork);
} else {
// MORE STUFF
opinions?

Related

Location Class returning empty location

I'm newcomer in Android development and I wish someone could help me.
My problem is as follow:
gradle
dependencies {
compile 'com.google.android.gms:play-services-maps:15.0.1'
compile 'com.google.android.gms:play-services-location:15.0.1'
}
MainActivity
[...]
local = (CheckBox) findViewById(R.id.local_checkbox);
local.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("DEBUG_INFO","CLICKED");
GPSTracker g = new GPSTracker(MainActivity.this);
if (((CheckBox) v).isChecked()) {
Log.v("DEBUG_INFO","CHECKED");
CheckGpsStatus();
if (GpsStatus == true) {
isLocated = true;
Location l = g.getLocation();
if ((l != null) && (isLocated == true)) {
lat = g.getLocation().getLatitude();
lon = g.getLocation().getLongitude();
Log.v("DEBUG_INFO","DEBUG_INFO:
Latitude: "+ String.valueOf(lat)+ " Longitude: "+
String.valueOf(lon));
}
else if ((l != null) && (isLocated == false)) {
lat = 0.0;
lon = 0.0;
} else {
lat = 0.0;
lon = 0.0;
}
} else {
new AlertDialog.Builder(NovaDenunciaActivity.this, R.style.AlertDialogCustom)
.setTitle("GPS TEXT!")
.setCancelable(false)
.setMessage("PLEASE SET GPS TEXT.")
.setPositiveButton("CLOSE",new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
local.toggle();
}
} else {
isLocated = false;
}
}
});
}//onCreate
public void CheckGpsStatus(){
locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("CHECKBOX","MARCADO");
}
} //Code end's
GPSTracker.java
[...]
public class GPSTracker extends Activity implements LocationListener {
Context context;
/*variables*/
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public GPSTracker(Context c) {
context = c;
}
/*variables*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} //Oncreate end's?
public Location getLocation() {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "No Permission Text!\nPlease allow
permissions text.", Toast.LENGTH_LONG).show();
return null;
}
//Get the location manager
locationManager = (LocationManager)
context.getSystemService(context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
Log.v("DEBUG_INFO:", "Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
//latituteField.setText("Location not available");
//longitudeField.setText("Location not available");
Log.v("DEBUG_INFO:", "Latitude: not available");
Log.v("DEBUG_INFO:", "Longitude: not available");
}
return location;
}
#Override
protected void onResume() {
super.onResume();
Log.v("DEBUG_INFO:", "REQUESTING LOCATION UPDATES");
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
Log.v("DEBUG_INFO:","STOP LOCATION UPDATES");
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
//latituteField.setText(String.valueOf(lat));
// longitudeField.setText(String.valueOf(lng));
Log.v("DEBUG_INFO:","Latitude: "+String.valueOf(lat));
Log.v("DEBUG_INFO:","Longitude: "+String.valueOf(lng));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(context, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(context, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
But when I click on checkbox the logcat (verbose) shows me the following:
V/DEBUG_INFO:: Latitude: not available
V/DEBUG_INFO:: Longitude: not available
The program should get latitude and longitude, if it does not exist it should call the locationManager.requestLocationUpdates(provider, 0, 0, this);
But I do not know what I'm doing wrong. Can someone help me?

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

GPS returning 0.0,0.0 as latitude and longitude on device,but working correctly on emulator

I am new to android. I am able to get the GPS co-ordinates from the emulator, but getting 0.0,0.0 as latitude and longitude in my device.
here is my code. Sorry its too long..
class GPSTracker.java
package com.example.spotter;
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
double accuracy;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1 meter
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 6 * 1; // 1 sec
// 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;
// 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();
Log.d("GPS Enabled", String.valueOf(latitude));
}
}
}
else{
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();
}
}
}
}
}
}
} 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
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public double getAccuracy(){
if(location != null){
accuracy = location.getAccuracy();
}
return accuracy;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
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) {
Log.d("spt", "in loc changed");
/*if (MainService.loststatus > 0) {
HttpPost httpPost = new HttpPost(
"http://spotter.orgfree.com/writegps.php?value="
+ String.valueOf(this.getLatitude()) + ","
+ String.valueOf(this.getLongitude()));
// output is the variable you used in your program
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.execute(httpPost);
Log.d("spt", "writing coord to file");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Toast.makeText(this, String.valueOf(gps.getLatitude()) + String.valueOf(gps.getLatitude()),
// Toast.LENGTH_SHORT).show();
}*/
}
#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;
}
}
and MainService.java
package com.example.spotter;
public class MainService extends Service implements Runnable {
String str;
Intent i1;
static double loststatus = 0;
Thread t;
//double longi,lati;
String provider;
Location location;
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Intent i = new Intent();
i.setClass(getApplicationContext(), Locked.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Log.d("spt", "in handler");
}
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
super.onDestroy();
stopService(new Intent(getBaseContext(), MainService.class));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Spotter tracking service has been activated.", Toast.LENGTH_SHORT).show();
Notification note=new Notification(R.drawable.ic_launcher,
"",
System.currentTimeMillis());
Intent i=new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi=PendingIntent.getActivity(this, 0,
i, 0);
note.setLatestEventInfo(this, "",
"",
pi);
note.flags|=Notification.FLAG_NO_CLEAR;
t = new Thread(this);
t.start();
startForeground(1337, note);
return START_STICKY;
}
public void run() {
Looper.prepare();
while (isMyServiceRunning()) {
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Log.d("spt", "read status started");
if ((Connectivity.isConnected(getApplicationContext()))) {
URL urlreadstatus = new URL("http://abc.xyz.com/status.txt");
// Log.d("spt",String.valueOf(URLUtil.isValidUrl("http://abc.xyz.com/status.txt")));
BufferedReader in = new BufferedReader( new InputStreamReader(urlreadstatus.openStream()));
str = in.readLine();
if(!str.equals(null)){
Log.d("spt", str);
}
in.close();
Log.d("spt", "read status complete");
} else {
Log.d("spt", "not connected");
break;
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
Log.d("spt", "IO exception");
str = "11";
e.printStackTrace();
} catch(NullPointerException e){
str="11";
}
if (str.equals(null)) {
str = "11";
}
if (str.length() == 1) {
loststatus++;
if(loststatus %10 ==0){
SendSms s= new SendSms();
Log.d("spt", "ghus gaye");
TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();
String no="15555215557";
if (getSimNumber != no)
{
//Log.d("spt", getSimNumber);
Log.d("spt", "ghus gaye dobara");
sendSMS();
}
}
GPSTracker gps=new GPSTracker(MainService.this);
Log.d("spt", "lost status1 requesting location updates");
Toast.makeText(this, String.valueOf(gps.getLatitude()) + String.valueOf(gps.getLatitude()),
Toast.LENGTH_SHORT).show();
if(loststatus==1){
handler.sendEmptyMessage(0);
}
if (loststatus > 0) {
HttpPost httpPost = new HttpPost(
"http://abc.xyz.com/writegps.php?value="
+ String.valueOf(gps.getLatitude()) + ","
+ String.valueOf(gps.getLongitude()));
HttpPost httpPost2 = new HttpPost(
"http://abc.xyz.com/writeaccuracy.php?value="
+ String.valueOf(gps.getAccuracy()));
// output is the variable you used in your program
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.execute(httpPost);
httpClient.execute(httpPost2);
Log.d("spt", "writing coord to file");
//gps.stopUsingGPS();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
loststatus = 0;
}
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.spotter.MainService".equals(service.service
.getClassName())) {
return true;
}
}
return false;
}
public void sendSMS() {
String phoneNumber = "15555215556";
GPSTracker gps=new GPSTracker(MainService.this);
String message =String.valueOf(gps.getLatitude())+","+String.valueOf(gps.getLongitude());
Log.d("spt", "in send sms");
// SmsManager smsManager = SmsManager.getDefault();
//smsManager.sendTextMessage(phoneNumber, null, message, null, null);
}
}
Please help.
You have several logic problems in your code
In if (isGPSEnabled), you are first asking for a current location and then checking if any old location is present. Same is the case in if (isNetworkEnabled).
Request for a new location takes some time few seconds to 20 minutes. So all the further steps should done in onLocationChanged() which you have left empty.
Since you are also asking for old location, chances are that somehow an old location bearing 0.0.0.0 is stored somewhere on your device which is giving you the false value.
Also you have not specified if you are asking for the required permission for using GPS properly.
update :-
As told by OP the problem was not a clear cell reception. Once under clear sky, he got correct GPS readings.

Making a Toast message from a separate Thread

I try to send a Toast Message from a Thread to the UIThread when clicking a button.
However, every time I click the button the Toast does not appear.
I am using a Handler to do this.
This is the full code, in case I made a major mistake somewhere:
package google.map.activity;
//imports
public class GoogleMapActivity extends MapActivity {
int lat = 0;
int lng = 0;
Location location;
MapController mc;
GeoPoint p;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.googlemapactivity);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(false);
mapView.setSatellite(false);
mapController = mapView.getController();
mapController.setZoom(19);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5,
0, new GeoUpdateHandler());
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 5, 0, new GeoUpdateHandler());
// //////---Switch to
// Start/////////////////////////////////////////////////////////////////////////////
Button switchToMain = (Button) findViewById(R.id.switchtomain);
switchToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
// ////--Call a
// Cab/////////////////////////////////////////////////////////////////////////////////////
Button getCab = (Button) findViewById(R.id.GetCab); // create the Button
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
getCab.setOnClickListener(new View.OnClickListener() {
String bestProvider = locationManager.getBestProvider(criteria,
true);
Location locationTest = locationManager
.getLastKnownLocation(bestProvider); // get
// last
// known
// location fix from
// locationManager
public void getAddress() {
String msg = null;
Looper.prepare();
if (locationTest == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager
.getLastKnownLocation(bestProvider);
Geocoder geocoder = new Geocoder(getBaseContext(), Locale
.getDefault());// create
// new
// GeoCoder
String result = null; // initialize result
try { // try to get Address list from location of bestProvider
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", "
+ address.getLocality();// set result
// to
// Streetname+Nr.
// and City
}
} catch (IOException e) {
msg = String.format("IOException!!");
} finally {
if (result != null) {
msg = String.format(result);
// Looper.loop();
} else
msg = String.format("Keine Position");
}
Message myMessage = new Message();
Bundle resBundle = new Bundle();
resBundle.putString("status", msg);
myMessage.obj = resBundle;
handler.sendMessage(myMessage);
}
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// Looper.myLooper();
// Looper.prepare();
getAddress(); // get the Address
Location locationTest = locationManager
.getLastKnownLocation(bestProvider);
if (locationTest == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location2 = locationManager
.getLastKnownLocation(bestProvider);
int lat = (int) (location2.getLatitude() * 1E6); // get
// position
// for GeoPoint
int lng = (int) (location2.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng); // create
// GeoPoint
// for
// mapController
mapController.animateTo(point);
}
}).start();
// toast.show();
}
});
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), msg.toString(),
Toast.LENGTH_LONG);
}
};
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Thank you in advance!
Edit: Solved it by using this:
Handler toastHandler = new Handler();
Runnable toastRunnable = new Runnable() {public void run() {Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();}};
In the UIThread and this:
toastHandler.post(toastRunnable);
in the background thread.
Try this:
runOnUiThread(new Runnable()
{
public void run()
{
// Here you can make a Toast
}
});
Your toast needs to be done in the UI thread. Here's how to do that:
Note: ClassName.this is needed because this by itself will refer to your anonymous Runnable class.
runOnUiThread(new Runnable() {
#Override
public void run()
{
Toast.makeText(ClassName.this, R.string.something, Toast.LENGTH_LONG).show();
}
});

User location cannot be found

I post a question not long ago. Basically what I am trying to do is have my location manager return my longitude and latitude. My getBestProvider() method returns network, however my locationManager.getLastKnownLocation(provider) returns null. As you can see I've implemented the listener. I must have done something wrong.
Here is the code.
public class Activity1 extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
readFile();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println(provider);
System.out.println(locationManager.getProviders(criteria, false));
System.out.println(locationManager.getProvider("network"));
System.out.println(locationManager.getAllProviders());
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
} else {
System.out.println("Provider not available");
System.out.println("Provider not available");
}
}#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
}
private void updateWithNewLocation(Location location){
String latLongString;TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else { latLongString = "No location found"; }
}

Categories

Resources