my application get crashed when gps turned off? - android

hi i am doing a application based on gps,i use gps as service for my project ,when gps is turn on it show the location correctly and application runs fine ,but after that i exit from my app completely and when the gps turned off the it shows crash message.which mean even if l leave or exit my app the service class is still running ,and also app get crash if i turn off gps when app is running ,but if i did not turn of gps it work fine.Now how can i solve this problem. i will show my service class used for gps
public class Gps_Service extends Service {
TextView txtv;
List<Address> myList;
String addressStr;
LocationManager lm;
LocationListener ll;
SQLiteDatabase DiaryDB = null;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("########### serviceOnCreate");
// Toast.makeText(this, "GPS Service started(Diary)", Toast.LENGTH_LONG).show();
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
#Override
public void onDestroy() {
super.onDestroy();
// Toast.makeText(this, "GPS Service Destroyed(Diary)", Toast.LENGTH_LONG).show();
lm.removeUpdates(ll);
System.out.println("########### inside ONDESTROY GPS listener removed");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
// Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
private class mylocationlistener implements LocationListener
{
public void onLocationChanged(Location location)
{
if (location != null) {
Geocoder myLocation = new Geocoder(Gps_Service.this, Locale.getDefault());
// Toast.makeText(MyService.this,location.getLatitude() + " " + location.getLongitude() +"\n",Toast.LENGTH_LONG).show();
// DiaryDB = MyService.this.openOrCreateDatabase("DIARY_DATABASE", MODE_PRIVATE, null);
// DiaryDB.execSQL("INSERT INTO Locations(LATITUDE, LONGITUDE) VALUES('" +location.getLatitude()+"','"+location.getLongitude()+"')");
// DiaryDB.close();
// ParseTweetsActivity.latitude = ""+location.getLatitude();
//ParseTweetsActivity.longitude = ""+location.getLongitude();
AndroidGoogleMapsActivity.lats = Double.parseDouble(""+location.getLatitude());
AndroidGoogleMapsActivity.longt = Double.parseDouble(""+location.getLongitude());
Advertiser_get_direction.latitudefrom = Double.parseDouble(""+location.getLongitude());
Advertiser_get_direction.longtitudefrom = Double.parseDouble(""+location.getLongitude());
AndroidGoogleMapsActivity.longt = Double.parseDouble(""+location.getLongitude());
System.out.println("saaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+AndroidGoogleMapsActivity.lats);
// ParseTweetsActivity.load();
try
{
myList = myLocation.getFromLocation(location.getLatitude(),location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if(myList!=null)
{
Address address = (Address) myList.get(0);
addressStr = "";
addressStr += address.getAddressLine(0) + "\n";
addressStr += address.getAddressLine(1) + "\n";
addressStr += "Country name "+address.getCountryName() + "\n";
addressStr += "Locality "+address.getLocality() + "\n";
addressStr += "Country code "+address.getCountryCode() + "\n";
addressStr += "Admin Area "+address.getAdminArea() + "\n";
addressStr += "SubAdmin Area "+address.getSubAdminArea() + "\n";
addressStr += "PostalCode "+address.getPostalCode() + "\n";
// txtv.append(location.getLatitude() + " " + location.getLongitude() +"\n");
// txtv.append(addressStr+"\n");
System.out.println(location.getLatitude() + " " + location.getLongitude() +"\n");
lm.removeUpdates(ll);
}
}
}
public void onProviderDisabled(String provider)
{
// Toast.makeText(MyService.this,"Provider Disabled",Toast.LENGTH_LONG).show();
txtv.setText("");
}
public void onProviderEnabled(String provider)
{
// Toast.makeText(MyService.this,"Provider Enabled.....",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}

You have declared a TextView within your Service. That's not good. TextView is a UI component and doesn't belong on the service.
In your onProviderDisabled() method, you call txtv.setText(""); which will probably crash because txtv is null. This is probably why your app is crashing when you disable GPS.

Change your code from
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
to following
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0,ll);
}

I had a problem like this when i didn`t release listener in the onDestroy().
Try to add the following code:
lm.unregisterListener(ll);

Related

Android GPS not Showing or writing to file

I have an app that monitors the accelerometer and the GPS and out puts them to a file.
I have defaulted the GPS to 0,0. But it doesn't seem to change.
public String location = "0 , 0";
public void onLocationChanged(Location arg0) {
arg0.getLatitude();
arg0.getLongitude();
location = arg0.getLongitude() + "," + arg0.getLatitude();
locationText = TextView.class.cast(location);
}
The text view is there to show if it is acutaully changing, but that doesn't seem to update either.
The location text view is at the top of the screen.
Im not sure what else I can include to help you help me. But if there is anything let me know.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
This is the code of the accelerometer, which works, and the GPS which doesn't.
Thanking you and a happy new year.
CODE
public class AccelOrientExample extends Activity implements SensorEventListener, LocationListener {
// Accelerometer X, Y, and Z values
private TextView accelXValue;
private TextView accelYValue;
private TextView accelZValue;
// Orientation X, Y, and Z values
private TextView orientXValue;
private TextView orientYValue;
private TextView orientZValue;
private TextView locationText;
private TextView toWrite;
public Toast myToast;
public String accel;
public int counter = 0;
public String orientData;
private LocationManager lm;
private Toast loc;
public String location = "0 , 0";
private SensorManager sensorManager = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a reference to a SensorManager
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.main);
// Capture accelerometer related view elements
accelXValue = (TextView) findViewById(R.id.accel_x_value);
accelYValue = (TextView) findViewById(R.id.accel_y_value);
accelZValue = (TextView) findViewById(R.id.accel_z_value);
// Capture orientation related view elements
orientXValue = (TextView) findViewById(R.id.orient_x_value);
orientYValue = (TextView) findViewById(R.id.orient_y_value);
orientZValue = (TextView) findViewById(R.id.orient_z_value);
// Initialize accelerometer related view elements
accelXValue.setText("0.00");
accelYValue.setText("0.00");
accelZValue.setText("0.00");
// Initialize orientation related view elements
orientXValue.setText("0.00");
orientYValue.setText("0.00");
orientZValue.setText("0.00");
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
/**/
// This method will update the UI on new sensor events
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
while(counter < 15)
{
if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION)
{
orientXValue.setText(Float.toString(sensorEvent.values[0]));
orientYValue.setText(Float.toString(sensorEvent.values[1]));
orientZValue.setText(Float.toString(sensorEvent.values[2]));
}
MyFile file = new MyFile();
file.createFile("OrientData.txt");
orientData = sensorEvent.values[0] + "," + sensorEvent.values[1] + "," + sensorEvent.values[2] + "\n";
file.write(orientData);
counter ++;
}
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
accelXValue.setText(Float.toString(sensorEvent.values[0]));
accelYValue.setText(Float.toString(sensorEvent.values[1]));
accelZValue.setText(Float.toString(sensorEvent.values[2]));
accel = sensorEvent.values[0] + "," + sensorEvent.values[1] + "," + sensorEvent.values[2] + ",";
}
}
}
public void onLocationChanged(Location arg0) {
synchronized (this) {
lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
arg0.getLatitude();
arg0.getLongitude();
location = arg0.getLongitude() + "," + arg0.getLatitude();
Toast.makeText(getApplicationContext(),"Test",Toast.LENGTH_LONG).show();
runOnUiThread(new Runnable(){
public void run() {
locationText.setText(location);
}
});
}
}
public void FileLogger(String accel, String location)
{
MyFile file = new MyFile();
file.createFile("RoadData.txt");
String toWrite = accel + location + "\n";
file.write(toWrite);
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String arg0) {
Log.e("GPS", "provider disabled " + arg0);
}
public void onProviderEnabled(String arg0) {
Log.e("GPS", "provider enabled " + arg0);
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
Log.e("GPS", "status changed to " + arg0 + " [" + arg1 + "]");
}
#Override
protected void onResume() {
super.onResume();
// Register this class as a listener for the accelerometer sensor
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
// ...and the orientation sensor
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
// Unregister the listener
sensorManager.unregisterListener(this);
super.onStop();
}
}
Can you try below
locationText.setText(location);
instead of
locationText = TextView.class.cast(location);
i expect locationText to be a TextView and
you requested location updates correctly and
added permission in manifest correctly and
the location update code is not getting executed by non-ui thread.
You might have the location services off, check that the provider is first available with;
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
Like #Javantor said you need to make sure that the manifest includes;
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and you are updating on the UI Thread. Try putting this in the onLocationUpdated code;
runOnUiThread(new Runnable(){
#Override
public void run() {
locationText.setText(location);
}
});
While it shouldn't make a difference, requesting the LocationManager this way;
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
with the time set to 0 instead of 1000ms ensures you get the updates as fast as they can come in.
Can you add some logging to the onLocationChanged method? That will let you know if the GPS data is being received at all.
Try launching Google Maps first and let it pinpoint your current location. Sometimes Location returns null because recent location list has been cleared. Also try this method to iterate over the currently enabled providers, not just the best one. This gives you a slightly higher chance or getting some coordinates returned. Hope this helps man. Good luck
private Location getLastKnownLocation() {
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
ALog.d("last known location, provider: %s, location: %s", provider,
l);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
ALog.d("found best last known location: %s", l);
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}

Cannot get current location coordinates

I want to get current longitude and latitude as int
So I use this code
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
....Notify
}
if (gps_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
if (network_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
locationManager.removeUpdates(this);
Unfortunately longitude and latitude are always null.
I have all permission needed in the manifest.
How can I fix this issue?
Well this is what i use for location listener
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class LocationUtils implements LocationListener{
Context context;
private String provider;
private LocationManager locationManager;
private String latitude="no value";
private String longitude="no value";
public LocationUtils(Context context) {
this.context=context;
// Get the location manager
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
latitude="no value";
longitude="no value";
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
/*Toast.makeText(context, "Provider " + provider + " has been selected.",
Toast.LENGTH_SHORT).show();*/
// System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
/*Toast.makeText(context, "Location not available",
Toast.LENGTH_SHORT).show();*/
}
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latitude = lat + "";
longitude = lng + "";
/* Toast.makeText(context, " lat: "+lat +" Long:"+lng,
Toast.LENGTH_SHORT).show(); */
}
#Override
public void onProviderDisabled(String provider) {
//Toast.makeText(context, "Disabled provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
//Toast.makeText(context, "Enabled new provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
}
Now in your activity u can get
LocationUtils appLocationManager = new LocationUtils(getContext());
String latitude = appLocationManager.getLatitude();
String longitude = appLocationManager.getLongitude();
Also add
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
in your manifest file
First check the GPS enabled in your device.
Check all the permissions included in the manifest
You are fetching the last known location using the GPS provider so remove that line and fetch the location individually for both the provider(There should be possible that your GPS is not available at that time so you did not get the location and you are fetching the last known location using the GPS so it can be null and if location will be null then it will not goes inside the conditions like if(network_enabled) and if(gps_enabled).).
In short check the Last known location of GPS if it is null then try to get the location using the Location provider and use that location.
public class SMS_Service extends Service {
private final String LOGTAG = "SMS_Service";
String latLongString;
String addressString;
double altitude;
int LAC;
int mcc = 0;
int mnc = 0;
String pn_no;
Altitude_Details ld = new Altitude_Details();
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.e(LOGTAG, "created");
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e(LOGTAG, "destroyed");
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e(LOGTAG, "started");
SmsManager sms = SmsManager.getDefault();
// get phone number from shared preference
SharedPreferences default1 = getSharedPreferences("Device",
MODE_WORLD_WRITEABLE);
pn_no = default1.getString("Phone_NO", "");
Log.e("phone_no in sms service", pn_no);
String From = intent.getStringExtra("From");
String Msg = intent.getStringExtra("Msg"); // get message from intent
Log.e("ON start:", "" + From);
Log.e("ON start:", "" + Msg);
String number = From.substring(7, 11);
Log.e("ON start: SUBSTRING", "" + number);
// check msg for Location keyword match or not
if (Msg.equals("LOCATION") && pn_no.equals(number)) {
Log.e("location:", "Location found");
TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tel.getNetworkOperator();
// find MNC and MCC
if (networkOperator != null) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
Log.e("MCC", "" + mcc);
Log.e("MNC", "" + mnc);
}
// find LAC for GSM
if (tel.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
final GsmCellLocation location = (GsmCellLocation) tel
.getCellLocation();
if (location != null) {
LAC = location.getLac();
Log.e("cell location", "LAC: " + location.getLac()
+ " CID: " + location.getCid());
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
// update method return latest location
updateWithNewLocation(location);
// location change then listner called
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
// send mcc,mnc,latitude,longitude,altitude,address,Link in message
String Url = "http://itouchmap.com/latlong.html";
sms.sendTextMessage(pn_no, null, "\nLocation:\n" + "MCC: " + mcc
+ "\nMNC: " + mnc + "\nLAC:" + LAC + latLongString
+ "\nAltitude:" + altitude + "feet"
+ "\nGo to Below site:\n" + Url, null, null);
sms.sendTextMessage(pn_no, null, "\nAddress:\n" + addressString,
null, null);
// stop service automatically
SMS_Service.this.stopSelf();
}
else {
Log.e("loation:", "Location not found");
SMS_Service.this.stopSelf();
}
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
// TODO Auto-generated method stub
addressString = "\nno address found";
// check location get or not from provider
if (location != null) {
// get latitude and longitude
double latitude = location.getLatitude();
double longitude = location.getLongitude();
latLongString = "\nLat:" + latitude + "\nLong:" + longitude;
Log.e("location", "" + latLongString);
// get altitude from method
altitude = ld.getElevationFromGoogleMaps(latitude, longitude);
Log.e("Altitude", "" + altitude);
// find address from latitude and longitude
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
}
addressString = sb.toString();
Log.e("Address", "" + addressString);
} catch (IOException e) {
}
} else {
latLongString = "\n No location found";
Log.e("location", "" + latLongString);
}
}
}
hey you can make the service and use this code to get altitude and latitude and decode this using class
Try This code
double longitude,latitude;
int lon,lat;
getcurrentloc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(GpsLocationFinder.this, "Enable Your GPS", Toast.LENGTH_LONG).show();
}else{
LocationResult locationResult=new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
longitude=location.getLongitude();
latitude=location.getLatitude();
lon=(int)longitude;
lat=(int)latitude;
Toast.makeText(GpsLocationFinder.this, "Current Longitude"+longitude+" Current Latitude"+latitude,Toast.LENGTH_LONG).show();
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(GpsLocationFinder.this, locationResult);
}
}
});
And the MyLocation Class is Below
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
double longitude,latitude;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
//Log.e("GPS DISTANCE","GPS Enabled");
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
//don't start listeners if no provider is enabled
//try{
try{
gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
}
try{
network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
}
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 100, locationListenerGps);
}
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 30000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.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) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.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() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.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: How to programmatically get raw data for GPS? (not js or html5 way)

I'm implementing my app which could get location for users. However, I found LocationManager didn't always work in all devices, you know, there are lots of different Android devices. Then I'm thinking about getting raw gps data and sending it to a location web service to get location back would be better.
After looked around over SO, I failed to get a robust solution, is there any idea? I'm really curious that how some GPS apps in market can work on every device.
Code Snippet
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListener locationListener = new MyLocationListener(locationManager);
locationListener.start();
Listener,
public class MyLocationListener implements LocationListener{
public static int PERMISSION_DENIED = 1;
public static int POSITION_UNAVAILABLE = 2;
public static int TIMEOUT = 3;
protected LocationManager locationManager;
protected boolean running = false;
public MyLocationListener(LocationManager locationManager )
{
this.locationManager = locationManager;
}
public void onProviderDisabled(String provider) {
Log.d(TAG, "Location provider '" + provider + "' disabled.");
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "Location provider "+ provider + " has been enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "The status of the provider " + provider + " has changed");
if (status == 0) {
Log.d(TAG, provider + " is OUT OF SERVICE");
}
else if (status == 1) {
Log.d(TAG, provider + " is TEMPORARILY_UNAVAILABLE");
}
else {
Log.d(TAG, provider + " is AVAILABLE");
}
}
public void onLocationChanged(Location location) {
Log.d(TAG, "The location has been updated!");
Log.d(TAG, "latitude = "+location.getLatitude()+" altitude = "+location.getAltitude());
}
public void start() {
if (!this.running) {
if (this.locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
this.running = true;
Log.d(TAG,"using gps");
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 600000, 0, this);
} else {
Log.d(TAG, "GPS provider is not available.");
}
}
if (!this.running) {
if (this.locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
this.running = true;
Log.d(TAG,"using network");
this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 600000, 10, this);
} else {
Log.d(TAG, "Network provider is not available.");
}
}
}
private void stop() {
if (this.running) {
this.locationManager.removeUpdates(this);
this.running = false;
}
}
/**
* Destroy listener.
*/
public void destroy() {
this.stop();
}
Sometimes, onStatusChanged simply got nothing.
LocationManager is The Only Approach. All devices have Android API - what not all devices have is GPS module inside. But you can check it using LocationManager as well.

Location listener in android gives java.lang.IllegalArgumentException: listener==null

Hey While I am running the application it gives a error java.lang.IllegalArgumentException: listener==null , that tells that listener is null.
My sample code is here:
public class HelloAndroidGpsActivity extends Activity {
private EditText editTextShowLocation;
private Button buttonGetLocation;
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buttonGetLocationClick();
}
});
}
/** Gets the current location and update the mobileLocation variable*/
private void getCurrentLocation() {
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
System.out.println("mobile location manager is ="+locManager);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
locListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
System.out.println("mobile location is in listener1");
}
#Override
public void onProviderEnabled(String provider) {
System.out.println("mobile location is in listener2");
}
#Override
public void onProviderDisabled(String provider) {
System.out.println("mobile location is in listener3");
}
#Override
public void onLocationChanged(Location location) {
System.out.println("mobile location is in listener="+location);
mobileLocation = location;
}
};
System.out.println("after setting listener");
}
private void buttonGetLocationClick() {
getCurrentLocation();
System.out.println("mobile location is ="+mobileLocation);
if (mobileLocation != null) {
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + mobileLocation.getLongitude();
String latitude = "Latitude: " + mobileLocation.getLatitude();
String altitiude = "Altitiude: " + mobileLocation.getAltitude();
String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
String time = "Time: " + mobileLocation.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n"
+ altitiude + "\n" + accuracy + "\n" + time);
} else {
editTextShowLocation.setText("Sorry, location is not determined");
}
}
}
Output in textbox is "Sorry, location is not determined""
If any one can tell me what is the problem then please help me.
Thank you
Initialize the listener before you use it.
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
At this point of time, locListener is null, and you are initializing it after this line of code. This may be the reason.
So rearrange the lines of your code like this;
locListener = new LocationListener() {...};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
Hope this may help to solve your issue...

Converting coordinates supplied by DDMS into location

I am creating a service that will give updates on the users location every 5 minutes. I am using the DDMS to send the coordinates to the emulator. I want to convert the coordinates and find the location. How can i do this? I am new to android Please help. This is my code so far
public class GetLocationService extends Service {
protected LocationManager locationManager;
Button start;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
LocationListener ll = new MyLocListener();
Location location = new Location("abc");
ll.onLocationChanged(location );
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, ll);
return START_STICKY;
}
private class MyLocListener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
}
Toast.makeText(GetLocationService.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
}
Try this:
try{
Geocoder geo = new Geocoder(youractivityclassname.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
yourtextfieldname.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
Log.d(TAG,addresses.get(0).getFeatureName() + ",
" + addresses.get(0).getLocality() +",
" + addresses.get(0).getAdminArea() + ",
" + addresses.get(0).getCountryName());
}
}
}
catch (Exception e) {
e.printStackTrace();
}

Categories

Resources