OnPause to stop GPS - android

UPDATE #2. My initial question was solved by the kindness of the two who answered. Apparently I need to start a new question for the fact that the resulting code, while it runs, does not stop the GPS. But there are no errors now so I would mark this as solved if I knew how :-)
UPDATE.
I have "working" code thanks to comments the only problem is that it doesn't do what it is supposed to do. It is working in that there are no errors.
To make it work, I added this globally at the top of the activity.
protected LocationListener ll;
protected LocationManager lm;
And used this OnPause code
#Override
protected void onPause() {
if(lm != null) {
lm.removeUpdates(ll);
}
ll = null;
lm = null;
super.onPause();
}
Everything compiles and runs on a phone. I get GPS locations displayed. Trouble is that the goal is to get the GPS to turn off so that the battery doesn't go dead after leaving the application. But the GPS stays on. I see this is a common complaint and have not seen an answer. I thought lm.removeUpdates(ll) was the solution but it isn't working.
--------------- original post -------------------------
I want to add some OnPause code to stop my GPS updates. I have tired at least a dozen examples of code from stackoverflow both questions and answers and all give errors in Eclipse.
My GPS code is here (it works fine):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLat = (TextView)findViewById(R.id.textLat);
textLong = (TextView)findViewById(R.id.textLong);
textTimex = (TextView)findViewById(R.id.textTimex);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
class mylocationlistener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
if (location != null)
{
double pLat = location.getLatitude();
double pLong = location.getLongitude();
long pTime = location.getTime();
DecimalFormat df = new DecimalFormat("#.######");
textLat.setText(df.format(pLat));
textLong.setText(df.format(pLong));
textTimex.setText(Long.toString(pTime));
//textTimex.setText(Long.toString(pTime));
//textTimex.setText(df.format(pLong));
}
}
#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
}
}
I am taking code from examples on the web and none of them work. Here is one
#Override
public void onPause() {
lm.removeUpdates(locationListener);
super.onPause();
}
It really doesn't matter what I call lm, it gives an error that it cannot resolve it. It doesn't matter which example code I use, none of them are error free.
I must be doing something very simply stupid...

declare locationListener globally(outside from onCreate method of Activity) as:
LocationListener ll;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
////your code...
ll = new mylocationlistener();
////your code..
}
#Override protected void onPause()
{
super.onPause();
// TODO Auto-generated method stub
System.out.println("a intrat in onPause()");
if(lm != null) {
lm.removeUpdates(ll);
}
ll = null;
lm = null;
}

The variables you are trying to use are just visible in the scope of onCreate. You need to use a member variable.
You need into your class a:
protected LocationListener ll;
protected LocationManager lm;
Then you just need to remove the LocationListener before your ll and use ll into your onPause code. And the same for lm and the type LocationManager.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLat = (TextView)findViewById(R.id.textLat);
textLong = (TextView)findViewById(R.id.textLong);
textTimex = (TextView)findViewById(R.id.textTimex);
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}

Related

Arcgis : how to get device location

Hie i tried to implement this codes in my application but it doesnt work , i dont know where i went wrong.
basically, when i launch the sample of the device location. it doesnt show me where is my current location and i dont see any blue dots that resembles the current location i am at.
the only thing that i see is the map . just a plain zoom out map.
I would be really thankful if someone who could help me out on how to get the current location with the blue dots that is displayed on the map..
this is my MainActivity.class
public class HelloWorld extends Activity {
MapView mMapView = null;
ArcGISTiledMapServiceLayer tileLayer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the map and initial extent from XML layout
mMapView = (MapView) findViewById(R.id.map);
mMapView.addLayer(new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"));
mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
public void onStatusChanged(Object source, STATUS status) {
if (source == mMapView && status == STATUS.INITIALIZED) {
LocationService ls = mMapView.getLocationService();
ls.setAutoPan(false);
ls.start();
}
}
});
}
protected void onPause() {
super.onPause();
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.unpause();
}
}
this is a code that draws my location every 1 second via provider and GPS .
let's first declare variables :
private GraphicsLayer myGraphicalLayer;
MapView mMapView;
ArcGISLocalTiledLayer baseLayer;
private LocationManager mlocManager;
private LocationListener mlocListener;
in onCreate function WE CALL LocationListener:
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mlocListener);
// loading the map
mMapView = (MapView) findViewById(R.id.localMap);
baseLayer = new ArcGISLocalTiledLayer(basemapurl);
mMapView.addLayer(baseLayer);
// defining my position layer
myGraphicalLayer = new GraphicsLayer();
then a function to draw my location :
private void SetMyLocationPoint(final double x, final double y) {
PictureMarkerSymbol myPin = new PictureMarkerSymbol(getResources().getDrawable(
R.drawable.mylocation_icon));
Point wgspoint = new Point(x, y);
Point mapPoint = (Point) GeometryEngine.project(wgspoint, SpatialReference.create(4326),
mMapView.getSpatialReference());
Graphic myPinGraphic = new Graphic(mapPoint, myPin);
try {
myGraphicalLayer.removeAll();
} catch (Exception e) {
e.printStackTrace();
}
myGraphicalLayer.addGraphic(myPinGraphic);
myGraphicalLayer.setVisible(true);
mMapView.addLayer(myGraphicalLayer);
}
make internal class that implements MyLocationListener to get you instant location, and let it call the function named SetMyLocationPoint like this way :
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
SetMyLocationPoint(loc.getLongitude(), loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "provider enabled", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "provider disabled", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
You need to use your own location manager or the location client to get the device's current location and then you will have to add that point on the map.
Your map should be in a MapFragment.
Get the googleMap object from the fragment and then add your custom blue dot on it.
LocationManager locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, listener);
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
if (location == null)
return;
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
}
}
#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
}
};
The above code gets you the location in onLocationChanged method.
Note: i have used GPS_PROVIDER to get the location.
There are other ways to get the current location too.

No respond when reading Android GPS

I want to read GPS data from Android. I have written some code follow online tutorial
public class MainActivity extends Activity
{
private DataCollection mDataCollection;
private LocationManager mLocationManager;
private Location mLocationGPS;
private String strLocationProvider = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Config.mContext = this;
mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
mLocationGPS = getLocationProvider(mLocationManager);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
}
protected void onResume()
{
super.onResume();
// mDataCollection.register();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
}
protected void onPause()
{
super.onPause();
// mDataCollection.unregister();
mLocationManager.removeUpdates(locationListener);
}
public void startCollection(View view)
{
// mDataCollection.register();
}
public void stopCollection(View view)
{
// mDataCollection.unregister();
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null)
{
double longitude = location.getLongitude();
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
private Location getLocationProvider(LocationManager lm){
Location retLocation = null ;
Criteria mCriteria01 = new Criteria();
mCriteria01.setAccuracy(Criteria.ACCURACY_FINE);
mCriteria01.setAltitudeRequired(false);
mCriteria01.setBearingRequired(false);
mCriteria01.setCostAllowed(true);
mCriteria01.setPowerRequirement(Criteria.POWER_HIGH);
strLocationProvider = lm.getBestProvider(mCriteria01, true);
retLocation = lm.getLastKnownLocation(strLocationProvider);
return retLocation;
}
}
When I put a break point atdouble longitude = location.getLongitude();, it never stop at that break point. I also have include the permission in manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.collectdata"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Could someone help me. Thanks in advance
Are you moving at least 10 meters while testing this? That's what the "10" means in mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
Also, you don't need that line in both onCreate() and onResume(). Just remove it from your onCreate() method (though it shouldn't cause problems, just is neater).
http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates(long, float, android.location.Criteria, android.app.PendingIntent)

android locationlistener carries on calling onlocationChanged after unregistering listener

I've an app that gets the user's location. I've registered the locationManager and listener in oncreate(). I've requested and removed updates in onResume() and onPause() respectively. The app finds the location and calls the getTime() on the loc object of onLocationChanged, this is to get an external time and then later compare to system time. This time is set in an applicationObject so that it's available app-wide. Everything works fine and i toast the time to the user from the applicationObject time setter method.
What i'm finding is that when i have found the time by getting a fix on the user's location, and i move to the next activity, the app continues to get the time for another 20 secs and sometimes more.
How can this be when i have unregistered the locaction listener in the first activity's onPause() method?
#Override
protected void onPause() {
mlocManager.removeUpdates(mlocListener);
super.onPause();
}
#Override
protected void onResume() {
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
super.onResume();
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
Log.e(TAG, "external time = " + loc.getTime());
DateTime dt = new DateTime(loc.getTime());
DateTimeFormatter df3 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String formattedNowTime3 = df3.print(dt);
Log.e(TAG, "formatted ext time = " + formattedNowTime3);
nfcscannerapplication.setExternalTime(dt);
}
#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
}
}//end of MyLocationListener
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entryscreen);
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
.
The onPause() may be called only after the new activity has started.
If you only want a single onLocationChange(), you can use requestSingleUpdate() and your problem is gone.
Regards.
Set mlocListener to null just after removeUpdates();

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.

Sending location to emulator

I am testing the option to send coordinates to the Android Emulator using the Built in Eclipse tool.But it doesn't seem to receive them.I have this simple code:
public class Main extends MapActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView view = (MapView) findViewById(R.id.themap);
view.setBuiltInZoomControls(true);
final MapController mp = view.getController();
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onLocationChanged(final Location location) {
// TODO Auto-generated method stub
mp.setCenter(new GeoPoint((int)location.getLatitude(), (int)location.getLongitude()));
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
I have the permissions for ACCESS_FINE_LOCATION and INTERNET in the Manifest.
If someone has any explanation I would be grateful.
Did you add
<uses-library android:name="com.google.android.maps" />
to the application tag in the manifest?
You also need a MD5 Fingerprint of the SDK Debug Certificate from Google to receive Google Maps data. You can get it here.
Try to put a breakpoint inside the onLocationChanged method and see if it stops when sending the location command to the emulator. this should also work when you don't have a certificate yet.
This works for me.
Listener implementation...
public class MyLocationListener implements LocationListener {
public static final String TAG = "MyLocationListener";
private Context context;
public MyLocationListener(Context c) {
this.context = c;
}
public void onLocationChanged(android.location.Location location) {
Log.d(TAG,"LocationChanged: Lat: "+location.getLatitude()+" Lng: "+location.getLongitude());
}
}
Usage...
MyLocationListener locationListener = new MyLocationListener(this);
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListener);

Categories

Resources