How to detect GPS being enabled - android

I'm making an app which uses GPS. The problem comes when you open the app without having GPS enabled, it does nothing (obviously) but if you enable GPS without exiting the app then the app still doing nothing. As I need to disable and enable GPS in my app I would need to know where the problem comes from, I'll leave you here some code:
public class EscuchaLocalizacion implements LocationListener {
private LocationManager gestor;
private TextView view1;
private TextView view2;
private boolean registrado;
private static final float minDistance = 10.0f;
private static final long minTime = 300;
public double _LONG;
public double _LAT;
EscuchaLocalizacion (Context c, TextView t1, TextView t2) {
Log.v("EscuchaLocalizacion", "Construyendo el objeto");
gestor = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
registrado = false;
view1 = t1;
view2 = t2;
Log.v("EscuchaLocalizacion", "He terminado de construir el objeto");
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
_LONG = arg0.getLongitude();
_LAT = arg0.getLatitude();
view1.setText(Double.toString(_LONG));
view2.setText(Double.toString(_LAT));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
if(arg0.contentEquals(LocationManager.GPS_PROVIDER)){
Log.w("EscucharLocalizacion","Provider: "
+ LocationManager.GPS_PROVIDER + " was disabled");
}
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
if(!registrado && arg0.contentEquals(LocationManager.GPS_PROVIDER)){
registrar();
}
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
public void registrar() {
if (gestor.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Log.i("EscucharLocalizacion", "Registrado a " + LocationManager.GPS_PROVIDER);
gestor.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime,
minDistance, this);
registrado = true;
}else {
Log.w("EscucharLocalizacion", "No se pudo registrar a " + LocationManager.GPS_PROVIDER);
registrado = false;
}
}
public void anularRegistro(){
gestor.removeUpdates(EscuchaLocalizacion.this);
registrado = false;
}
}

where do you initialize EscuchaLocalizacion?
You need to search location in onResume () and stop searching onPause location in your activity.
start locating:
escuchaLocalizacion.requestLocationUpdates(LocationManager.GPS_PROVIDER, 00, 0, gpsLocationListener);
stop locating:
escuchaLocalizacion.removeUpdates(gpsLocationListener);
If you have a checkbox to enable/disable GPS localisation, you can add a listener on the checkbox then put this functions there if you want to use GPS or not.
Also don't forget to add this in the manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

Related

Location updates using Android GPS?

I created a class to use the LocationListener but I am getting classCastException when I request for location updates
This is my class code
public class Loc implements
LocationListener, GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
// A request to connect to Location Services
private LocationRequest mLocationRequest;
// Stores the current instantiation of the location client in this object
private LocationClient mLocationClient;
/*
* Note if updates have been turned on. Starts out as "false"; is set to
* "true" in the method handleRequestSuccess of LocationUpdateReceiver.
*/
boolean mUpdatesRequested = false;
// Milliseconds per second
public static final int MILLISECONDS_PER_SECOND = 1000;
// The update interval
public static final int UPDATE_INTERVAL_IN_SECONDS = 10;
// A fast interval ceiling
public static final int FAST_CEILING_IN_SECONDS = 1;
// Update interval in milliseconds
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// A fast ceiling of update intervals, used when the app is visible
public static final long FAST_INTERVAL_CEILING_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* FAST_CEILING_IN_SECONDS;
Location currentLocation ;
LocationListener locListener;
Context x;
public Loc(Context con) {
// Create a new global location parameters object
this.x=con;
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mLocationClient = new LocationClient(con, this, this);
}
public void stop() { // If the client is connected
if (mLocationClient.isConnected()) {
stopPeriodicUpdates();
}
// After disconnect() is called, the client is considered "dead".
mLocationClient.disconnect();
}
public void start() {
mLocationClient.connect();
}
public void startUpdates() {
mUpdatesRequested = true;
startPeriodicUpdates();
}
public Location getLocation() {
// Get the current location
currentLocation = mLocationClient.getLastLocation();
// Display the current location in the UI
Log.e("lat log", "" + currentLocation.getLatitude() + " , "
+ currentLocation.getLongitude());
return currentLocation;
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
currentLocation=location;
Log.e("lat log", "" + currentLocation.getLatitude() + " , "
+ currentLocation.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
private void stopPeriodicUpdates() {
mLocationClient
.removeLocationUpdates((com.google.android.gms.location.LocationListener) this);
}
private void startPeriodicUpdates() {
mLocationClient.requestLocationUpdates(mLocationRequest,(com.google.android.gms.location.LocationListener) this);
}
}
This is my activity code
public class MainActivity1 extends Activity {
Loc l;
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1);
t=(TextView)findViewById(R.id.txt);
l = new Loc(getApplicationContext());
l.start();
}
public void getLoc(View v) {
// l.getLocation();
l.startUpdates();
}
I am getting my lat and long perfectly fine.
But my issue is with for location updates
I get this error
Caused by: java.lang.ClassCastException: com.example.gps.Loc cannot be cast to com.google.android.gms.location.LocationListener
I do get that I cannot pass LocationListener like this
mLocationClient.requestLocationUpdates(mLocationRequest,(com.google.android.gms.location.LocationListener) this);
But how should I exactly pass it??
Only needed to add the interface
com.google.android.gms.location.LocationListener
like this.
public class Loc implements
GooglePlayServicesClient.ConnectionCallbacks
,GooglePlayServicesClient.OnConnectionFailedListener
,com.google.android.gms.location.LocationListener {
//...
}

Updating Activity with Latitude/Longitude values returned from a Service

I'm trying to write a simple app that updates the MainActivity with the Lat/Lng values returned by the service. But it always returns the null value. I have added permissions and added TheService.java as service in AndroidManifest.xml file...Kindly tell me where I have gone wrong.
MainActivity.java
public class MainActivity extends Activity {
TextView tv1, tv2;
IntentFilter filter;
receive rec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 =(TextView)findViewById(R.id.textView1);
tv2 = (TextView)findViewById(R.id.textView2);
filter = new IntentFilter("Updated");
rec = new receive();
Intent gps_int = new Intent(this,TheService.class);
startService(gps_int);
}
#Override
public void onPause()
{
super.onPause();
unregisterReceiver(rec);
}
#Override
public void onResume()
{
super.onResume();
rec = new receive();
registerReceiver(rec, filter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class receive extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
tv1.setText(intent.getExtras().getString("lat"));
tv2.setText(intent.getExtras().getString("lon"));
Toast.makeText(getApplicationContext(), "Toast Executed", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "BR Latitude "+intent.getExtras().getString("lat"),Toast.LENGTH_SHORT).show();
}
}}
TheService.java
public class TheService extends Service implements LocationListener {
LocationManager lm;
Location loc;
double lat = 0;
double lon = 0;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
lm=(LocationManager)getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
onLocationChanged(loc);
return START_STICKY;
}
#Override
public void onCreate()
{
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
updateui(location);
}
private void updateui(Location location) {
// TODO Auto-generated method stub
lat = location.getLatitude();
lon = location.getLongitude();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent gps_intent = new Intent("Updated");
gps_intent.putExtra("lat", lat);
gps_intent.putExtra("lon", lon);
sendBroadcast(gps_intent);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}}
You should use the Google Play Services for the location, that's easier to handle.
What for do you even need a Service? Having a location listener in your Activity is totally fine.
If you want to stay with the Service, than bind the Activity to it, instead of using a Broadcast.

native_start failed in startNavigating android GPS

I am new to android development. I am trying to get the Location using GPS in android. I have adopted two classes: one for the GPSTracker and the other one for the Activity. The location is getting set as null everytime and when i checked in LogCat, i get the following error:
native_start failed in startNavigating
I have set the permission in the manifest for GPS data as well. I even tried to pass fake latitude and longitude by using the emulator control, to no effect. what might be the reason? I am coding for the Android 2.3
My code is: //GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context mcontext;
boolean isGPSEnabled = false;
boolean canGetLocation = false;
double latitude,longitude;
Location location;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
protected LocationListener listener;
public GPSTracker(Context context){
this.mcontext = context;
getLocation();
}
public Location getLocation() {
try{
locationManager = (LocationManager) mcontext.getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location1) {
// TODO Auto-generated method stub
location = location1;
}
};
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
if(isGPSEnabled){
this.canGetLocation = true;
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);
Log.d("GPS", "Enabled");
if(locationManager!=null){
location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
if(location!=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
//Log.d("Latitude", latitude.toString());
//Log.d("Longitude", longitude.toString());
}
else{
Log.d("Location","Null");
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return location;
// TODO Auto-generated method stub
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mcontext);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mcontext.startActivity(intent);
}
});
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 arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public double getLatitude() {
// TODO Auto-generated method stub
if(location!=null){
Log.d("Location",location.toString());
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
// TODO Auto-generated method stub
if(location!=null){
Log.d("Location",location.toString());
longitude = location.getLongitude();
}
return longitude;
}
}
//LocationActivity.java
public class LocationActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
GPSTracker gps = new GPSTracker(LocationActivity.this);
if(gps.canGetLocation() == false){
Log.d("GPSLogFromActivity","False");
gps.showSettingsAlert();
}
else{
double latitude = gps.getLatitude();
System.out.println("Latitude: "+latitude);
double longitude = gps.getLongitude();
System.out.println("Longitud: e"+longitude);
Log.d("GPSLogFromActivity","True");
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
}
});
hey friend have look on this
My current location always returns null. How can I fix this?

Changing the GPS coordinates with out moving anywhere

**i have used the gps coordinates for calculating the distance using location updates. but problem is that if i am standing at same place the coordinates changes and distance is changing with out moving anywhere. I want to change it only when I have moved min 10 mtrs.
## Activity ##
//Activity
public TextView dist;
public double lati1,lati2,longi1,longi2;
private boolean run1 = false;
private Handler handler1 = new Handler();
private Runnable task1 = new Runnable() {
public void run() {
// TODO Auto-generated method stub
if (run1) {
handler1.postDelayed(this,1000);
if(lati1==0.0&&longi1==0.0)
{
lati1=Service1.lat1;
longi1=Service1.lon1;
}
lati2=Service1.lat1;
longi2=Service1.lon1;
double R=63710;
double dLat=Math.toRadians(lati2-lati1);
double dLon=Math.toRadians(longi2-longi1);
double a=Math.sin(dLat/2)*Math.sin(dLat/2)+
Math.cos(Math.toRadians(lati1))*Math.cos(Math.toRadians(lati2))*
Math.sin(dLon/2)*Math.sin(dLon/2);
double c=2*Math.asin(Math.sqrt(a));
double d=R*c;
d=(double)(Math.round(d*100.00))/1000.00;
distance+=d;
String s=String.format("%.2f", distance);
dist.setText(s);
lati1 = lati2;
longi1 = longi2;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dist=(TextView)findViewById(R.id.distancetextView);
Intent i = new Intent(context, Service1.class);
startService(i);
}
## Service ##
//Service
private double new_latitude = 0.0;
private double new_longitude = 0.0;
public static double lat1=0.0,lon1=0.0;
LocationManager locationManager = null;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0f, this);
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
locationManager.removeUpdates(this);
super.onDestroy();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
new_latitude=location.getLatitude();
new_longitude=location.getLongitude();
lat1=new_latitude;
lon1=new_longitude;
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}****
I should see the code you are writing. But without it I can say that there is a function, that you call, and it give you location update each X milliseconds. Or you can get the latest updated location, again, I should see your code.
UPDATE:
change this line
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0f, this);
to
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 10.0f, this);
You'll receive updates after moving 10m.
The second parameter is time in millisecond, the third is minimum distance. But it doesn't mean you'll get update exactly at the requested time or requested distance, but rather about it.
//Public or class variable of previous speed initialised on class.
// float previousSpeed;
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
new_latitude=location.getLatitude();
new_longitude=location.getLongitude();
float speed = location.getSpeed();
//You could also use location.hasSpeed(), which is a boolean, but it almost
//always returns True
if(speed > DESIRED_LIMIT && previousSpeed > DESIRED_LIMIT){
lat1=new_latitude;
lon1=new_longitude;
}
previousSpeed = speed;
}
So something like that. That condition is not very well optimized or designed. But that is how you get GPS speed from location object. You can tweak the speed limit or the whole condition to get the best results. Or add even more history of speed to monitor.
You can use the location spoofer application from the android market and specify the duration of spoofing the location and also the distance

Android: How to get GPS data without using a MapView?

I am trying to get GPS data without using map view.The code that I have below is from O'Rielly's Programming Android book and is supposed to work but is not. I am using an Android 2.2.1 phone and the app closes immediately after it starts.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvLattitude = (TextView) findViewById(R.id.tvLattitude);
tvLongitude = (TextView) findViewById(R.id.tvLongitude);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
tvLattitude.setText(Double.toString(loc.getLatitude()));
tvLongitude.setText(Double.toString(loc.getLongitude()));
locListenD = new DispLocListener();
lm.requestLocationUpdates("gps", 30000L, 10.0f, locListenD);}
private class DispLocListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
tvLattitude.setText(Double.toString(location.getLatitude()));
tvLongitude.setText(Double.toString(location.getLongitude()));}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
lm.removeUpdates(locListenD);}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
lm.requestLocationUpdates("gps", 30000L, 10.0f, locListenD);}
Perhaps you need to add the permissions
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
to your manifest?
Well, I set up a similar project and found a problem with your code: in onCreate you immediately try to set the location from previous locations (which on first run obviously wouldn't be available). I erased those lines and the code seems to run fine
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvLattitude = (TextView) findViewById(R.id.tvLattitude);
tvLongitude = (TextView) findViewById(R.id.tvLongitude);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locListenD = new DispLocListener();
lm.requestLocationUpdates("gps", 30000L, 10.0f, locListenD);
}
private LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateNearestLocation(location);
}
private boolean updateNearestLocation(Location lastKnownLocation) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
LocationManager m_locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
try {
m_locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} catch (IllegalArgumentException iae) {
Log.i(TAG, "Could not find a location provider");
return false;
}
if (lastKnownLocation == null) {
lastKnownLocation = m_locationManager
.getLastKnownLocation(locationProvider);
} else {
m_locationManager.removeUpdates(locationListener);
}
if (lastKnownLocation != null) {
lastKnownLocation.getLatitude();
lastKnownLocation.getLongitude();
}
}
Perhaps you need to turn on the locations in your phone's settings:
Settings --> Location and Security --> My Location
Also if you are using an emulator keep in mind it won't generate location data unless you do it manually through the DDMS.

Categories

Resources