Fetch first location on android and stop updates - android

I still have problem with fetching first location on android. I am using Criteria like
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setSpeedRequired(true);
String provider = lm.getBestProvider(criteria, true);
if(provider!=null && provider.length()>0){
lm.requestLocationUpdates(provider, 0, 0, this);
}
I need to stop when first time get location like lm.removeUpdates(this);
Where to put that line of code ? In onLocationChanged ?

Yes. onLocationChanged will be called on each location update. If you want one only, you can remove it there.

public class GPSLocatorActivity extends Activity {
double current_lat, current_lng;
MapView mapView;
boolean flag = true;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1,
mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
current_lat = loc.getLatitude();
current_lng = loc.getLongitude();
if (flag == true) {
flag = false;
go(current_lat, current_lng);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled !!! Please Enable It.",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}/* End of Class MyLocationListener */
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
public void go(double c_lat, double c_lng) {
System.out.println("your current Lat :: " + c_lat);
System.out.println("your current Lng :: " + c_lng);
/*turn of gps now */
turnGPSOff();
}
private void turnGPSOff() {
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
}/* End of UseGps Activity */

Related

How can we get the location in android without turning on GPS

How can we retrieve the location in android with out turning on GPS. I was able to get the location using the GPS,NETWORK Providers. When the GPS was disabled not able to get the coordinates. Could anyone help me out. Thanks in advance
Go through this tutorial.
http://www.vogella.com/tutorials/AndroidLocationAPI/article.html
Here is the sample code you can use to retrieve location from default location provider.
public class ShowLocation extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
}
/* Request updates at startup */
#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) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
}
#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, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Add the following permissions to your application in your AndroidManifest.xml file
INTERNET
ACCESS_FINE_LOCATION
ACCESS_COARSE_LOCATION
I hope this helps.
Getting Location using network providers:
boolean network_enabled = isNetworkAvailable();
Location location = null;
LocationManager locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if(network_enabled)
location = SLOC_locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
The isNetworkAvailabel() function:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) SLOC_context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Running GPS Values

I'm trying to get GPS values every few seconds and I'm missing some trick. Here's what I've tried:
public class Locn extends ActionBarActivity
{
private LocationManager locationManager;
private String provider;
private Location loc = null;
private Criteria criteria;
... local variables ...
#Override
protected void onCreate(Bundle savedInstanceState)
{
...
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled. If not send user to the GPS settings
if (!enabled)
{
Toast.makeText(this, "Please enable GPS location service",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else
{
Toast.makeText(this, "GPS location service is enabled",
Toast.LENGTH_SHORT).show();
}
// Define the criteria to select the location provider -> use default
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
// Let Android select the best location provider based on criteria
provider = locationManager.getBestProvider(criteria, true);
...
}
//--------------------------------------
// Set up timer handlers
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable()
{
#Override
public void run()
{
provider = locationManager.getBestProvider(criteria, true);
loc = locationManager.getLastKnownLocation(provider);
milli = System.currentTimeMillis();
longitude = loc.getLongitude();
latitude = loc.getLatitude();
count++;
timerHandler.postDelayed(this, 2000);
}
};
count and milli changes every two seconds but the latitude and longitude do not change at all. (Yes, I'm changing position -- up to 2 miles)
What am I missing here? Does loc have to be cleared before calling getLastKnownLocation again?
Thanks,
Walt
Timer tm =new Timer();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
tm.schedule(new task(),10,10000);//this execute task every 10 seconds
//use the timer task in your main activity
class task extends TimerTask {
public void run() {
Home.this.runOnUiThread(new Runnable() {
public void run() {
longitude = loc.getLongitude();
latitude = loc.getLatitude();
});
}
};
You don't need a Timer. Just use LocationManager.requestLocationUpdates()
From Android documentation:
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
See at: Android LocationManager
Just use like below:
public class MainActivity extends Activity implements LocationListener {
private String provider;
private LocationManager lm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
}
#Override
protected void onResume() {
super.onResume();
lm.requestLocationUpdates(provider, 1000, 10, this);
}
#Override
protected void onPause() {
super.onPause();
lm.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

Sometimes I am getting empty location until I restart my phone why?

So I am getting the longitude and latitude as:
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude=location.getLongitude();
latitude=location.getLatitude();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Or use LocationManager.GPS_PROVIDER
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation!=null){
longitude=lastKnownLocation.getLongitude();
latitude=lastKnownLocation.getLatitude();
}
then I am getting my location depending on these info:
Geocoder myLocation = new Geocoder(Time.this, Locale.getDefault());
List<Address> myList=null;
try {
myList = myLocation.getFromLocation(latitude,longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(myList != null && myList.size()>0) {
address= (Address) myList.get(0);
if(address.getAddressLine(0)!=null){
addressStr += address.getAddressLine(0);
}
if(address.getAddressLine(1)!=null){
addressStr += ", "+address.getAddressLine(1);
}
if(address.getAddressLine(2)!=null){
addressStr += ", " +address.getAddressLine(2);
}
}
But sometimes the location stays null until I restart my phone why that's happening? and is there a way to fix it?
Try to setup your Location Listener as below :
public class BasicMapActivity_new2 extends Activity implements
LocationListener {
private LocationManager locationManager;
private String provider;
Double Latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new2.this, "GPS signal not found",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else if (!enabledWiFi) {
Toast.makeText(BasicMapActivity_new2.this,
"Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) 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);
if (location != null) {
onLocationChanged(location);
} else {
// do something
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
Location old_one;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
// Toast.makeText(BasicMapActivity_new.this, "Location " + lat+","+lng,
// Toast.LENGTH_LONG).show();
LatLng coordinate = new LatLng(lat, lng);
Latitude = lat;
longitude = lng;
Toast.makeText(BasicMapActivity_new2.this,
"Location " + coordinate.latitude + "," + coordinate.longitude,
Toast.LENGTH_LONG).show();
}
#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
}
}
And do not forget to add permission into manifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Update: This is because to add requestLocationUpdates() into onResume() and removeUpdates(this); into onPause(). This way your app will stop updated locations when it is not active. add below into your Activity:
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
this is a documented issue in google forums. Check this thread:
https://code.google.com/p/android/issues/detail?id=57707
Also i think the solution for this is to use Google Location API, this requires that you have Google Play services up to date and >= 2.2 i think. Hope this helps you. I battled this issue for long

GPS location never aquired

I am trying to get the GPS location in android, and run an ASYNC task with the gps coordinates. My location class is not just stalling the app with gps on. I am not getting a gps coordinate back.
My activity which tries to get the gps location is:
public class FindBrewery extends ActionbarMenu {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beer_location_list);
String title = "Nearby Breweries";
TextView topTitle = (TextView) findViewById(R.id.beerLocationTitle);
topTitle.setText(title);
//get user location
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
///new code
LocationManager mlocManager=null;
LocationListener mlocListener;
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if(MyLocationListener.latitude>0)
{
double longitude = MyLocationListener.latitude;
double latitude = MyLocationListener.longitude;
Toast.makeText(getApplicationContext(), "inside gps if", Toast.LENGTH_LONG).show();
//get gps results
//construct url
String url = "myURL";
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
else
{
//not sure what to put here yet...
}
} else {
Toast.makeText(getApplicationContext(), "GPS is Not Turned on", Toast.LENGTH_LONG).show();
}
}
//new code end
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
}
MyLocationListener Class:
package com.example.beerportfoliopro;
/**
* Created by Mike on 11/26/13.
*/
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude=loc.getLatitude();
longitude=loc.getLongitude();
}
#Override
public void onProviderDisabled(String provider)
{
//print "Currently GPS is Disabled";
}
#Override
public void onProviderEnabled(String provider)
{
//print "GPS got Enabled";
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
I know it is getting stuck in MyLocationListenerClass because I am not getting to my toast at all.
Udate:
I tried adding getters to MyLocationListenerClass:
public double getLatitude(){
return latitude;
}
public double getLongitude(){
return longitude;
}
But when Igo back to my activity which calls all this I try:
double latitude = mlocListener.getLatitude();
Bt I get a cannot resolve method error on getLatitdue()
I think this is the problem:
you are calling the Class instead (MyLocationListener) of calling the instance of the class mlocListener
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if(MyLocationListener.latitude>0)
{
double longitude = MyLocationListener.latitude;
double latitude = MyLocationListener.longitude;
Toast.makeText(getApplicationContext(), "inside gps if", Toast.LENGTH_LONG).show();
//get gps results
//construct url
String url = "myURL";
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
try doing this :
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if(mlocListener.latitude>0)
{
double longitude = mlocListener.latitude;
double latitude = mlocListener.longitude;
Toast.makeText(getApplicationContext(), "inside gps if", Toast.LENGTH_LONG).show();
//get gps results
//construct url
String url = "myURL";
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
This should work

GeoLocation identification before first change

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
I find the onLocationChanged function is PERFECTLY working when the location is Changed with the above code.
///////CLASS mylocationlistener
private class mylocationlistener implements LocationListener {
//#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Toast.makeText(MainActivity.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
p = new GeoPoint((int)location.getLatitude(),(int)location.getLongitude());
// p = new GeoPoint((int)8.538754,(int)76.950620);
}
}
//#Override
public void onProviderDisabled(String provider) {
}
// #Override
public void onProviderEnabled(String provider) {
}
// #Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
But the Problem is that I want the variable "p" to be filled with the current location , when the program starts, that is Before the First Change Help !!
try this code:
locationManager = (LocationManager) 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.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
System.out.println("Location not avilable");
}
}
/* Request updates at startup */
#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) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
Log.i(TAG, "Lattitude:" +lat);
Log.i(TAG, "Longitude:" +lng);
}
Before you get fix, you can use coarse location. Check this link:
http://devdiscoveries.wordpress.com/2010/02/04/android-use-location-services/

Categories

Resources