Running GPS Values - android

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

Related

android get location in background and update listview

I'm trying to program an application which is using the current location from the user and calculating the distance and writes it into my listview.
The location doesn't have to be very accurate and i only want to fetch a new location when the list is refreshed or on app start, not continously.
My problem is that the locationlistener with gps takes too long to find a location and i have to update my list a lot before it is showing the right distance.
I was thinking about implementing a background task which gets the location and updates the list automatically when it found the position. Would that be a solution?
Is there any option to get a location faster, even if it is not as accurate as gps?
what i have so far on my location listener:
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
myLoc.setLatitude(lat);
myLoc.setLongitude(lng);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
in this method i'm calling the locationmanager and listener and creating the listview with the distance
public void getList(){
locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
//... creating the list with distance and so on
}
i hope you can give me some hints how i can implement this that i will work as described above or tell me what i should use instead.
thanks :)
1). You can use LocationManager.NETWORK_PROVIDER
This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.
eg:- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 50, locationListener);
2). If you want to use background task then use this service
public class LocationFinder extends Service {
public static double lat, lng;
LocationManager locationManager;
public void onDestroy() {
super.onDestroy();
if (locationManager != null && locationListener != null) {
locationManager.removeUpdates(locationListener);
}
}
#Override
public void onCreate() {
Log.v("location", "===>location ed onCreate " + lat);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.v("location", "===>location ed onStartCommand " + lat + "==>" + lng);
new Handler().post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
getLocation();
}
});
return START_STICKY;
}
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 getLocation() {
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
if (locationManager != null) {
String provider = locationManager.getBestProvider(criteria, true);
if (provider != null) {
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 500, 50, locationListener);
} else {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 50, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 50, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 500, 50, locationListener);
}
}
}
}
private void updateWithNewLocation(Location location) {
if (location != null) {
Log.v("location", "===>location ed " + lat);
lat = location.getLatitude();
lng = location.getLongitude();
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

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

Not getting current location

I'm trying to get the current location and sending its LAt and LON to another class.But my application is not getting the current location it is showing the LAST LOCATION.Please help me out how to get the current location using GPS and NETWORK provider.
Below is the code:
public class location implements LocationListener
{
private LocationManager mgr;
private String best;
Location location;
public static double myLocationLatitude;
public static double myLocationLongitude;
public void locUpdate(Context context)
{
mgr = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// criteria.setAccuracy(Criteria.ACCURACY_COARSE);
best = mgr.getBestProvider(criteria, true);
mgr.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,0,0,this);
try{
Location location = mgr.getLastKnownLocation(best);
Intent i = new Intent();
i.setClass(context,sentsms.class);
i.putExtra("latitude", location.getLatitude());
i.putExtra("longitude", location.getLongitude());
i.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Launch the new activity and add the additional flags to the intent
context.getApplicationContext().startActivity(i);
}
catch(Exception e)
{
}
}
public void onLocationChanged(Location location) {
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
protected void onPause()
{
// super.onPause();
mgr.removeUpdates(this);
}
protected void onResume() {
// super.onResume();
mgr.requestLocationUpdates(best, 15000, 10, this);
}
private void dumpLocation(Location l) {
if (l != null){
myLocationLatitude = l.getLatitude();
myLocationLongitude = l.getLongitude();
}
}
}
From the docs for getLastKnownLocation():
Returns a Location indicating the data from the last known location
fix obtained from the given provider.
This can be done without starting the provider. Note that this
location could be out-of-date, for example if the device was turned
off and moved to another location.
If the provider is currently disabled, null is returned.
This means getLastKnownLocation() will retrieve the Location based on the last fix of the Provider. If you want updated Locations, use the Location received in onLocationChanged()
Please try this way
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
if (provider != null) {
location = locationManager.getLastKnownLocation(provider);
// locationManager.requestLocationUpdates(provider, 1000*60*60,
// 1000, this);
// update only in 1 hour and 1 km of distance
locationManager.requestLocationUpdates(provider, 100, 1, this);
}

keep application running in background

I want to keep my application running in background
I have an application that sends the user's location to our server
I have the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
updateWithNewLocation(null);
locationManager.requestLocationUpdates(provider, (10*60*1000), 10,
locationListener);
}
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){ }
};
public void updateWithNewLocation(Location location) {
if (location != null) {
Dbhelper helper = new Dbhelper(this);
final SQLiteDatabase db = helper.getWritableDatabase();
long time = System.currentTimeMillis();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
final String curTime = df.format(time);
final double lat = location.getLatitude();
final double lng = location.getLongitude();
final double alt = location.getAltitude();
System.out.println(lat);
System.out.println(lng);
System.out.println(alt);
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
db.close();
/*Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('121.2149012','-6.217837','0.0','2012-05-07 10:20:01')");
db.close();
}
}, 10*60*1000, 10*60*1000);*/
}
}
I want my applicatioin to be running in the background. I want it to launch automatically when the phone is turned on
A very simple answer for your problem is to use Service. It will allow you to perform variety of tasks while being in background and is your best bet for sending your location to server silently.
Read this answer for help.
You can keep your application running in the background using Service
I hope this link will help you
Please read the documentation for further details
Run your background logic in a Service, and if you want to give a good UX experience (and to also have an higher priority) post a Notification to status-bar (using NotificationManager).
GrabLocationDetails.java
Use this code as your GrabLocationDetails.java
public class GrabLocationDetails extends Service implements LocationListener {
double lat,lng;
private LocationManager locationManager;
private String provider;
boolean isGps;
private ArrayList<String> mList;
Context GLDContext;
public GrabLocationDetails(Context cont){
this.GLDContext=cont;
}
public GrabLocationDetails(){}
#Override
public void onCreate() {
super.onCreate();
mList = new ArrayList<String>();
isGps = false;
lat=0.0;
lng=0.0;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//super.onStart(intent, startId);
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
isGps = false;
ListAddItem(isGps);
SendBroadcast();
} else {
isGps = true;
Location location = locationManager.getLastKnownLocation(provider);
lat=(location.getLatitude());
lng=(location.getLongitude());
ListAddItem(true);
SendBroadcast();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
} catch (Exception e) {
ListAddItem(isGps);
SendBroadcast();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
//locationManager.removeUpdates(this);
}
public void SendBroadcast(){
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(CommandExecutionModule.LocationDetails);
broadcastIntent.putExtra("Data", mList);
sendBroadcast(broadcastIntent);
}
public void ListAddItem(boolean GPS) {
//if(!GPS)
//mList.add("0");
//else
//mList.add("1");
mList.add(Double.toString(lat));
mList.add(Double.toString(lng));
}
/**************************************************************************************************************/
#Override
public void onLocationChanged(Location location){
locationManager.requestLocationUpdates(provider, 400, 1, this);
mList.clear();
lat = (location.getLatitude());
lng = (location.getLongitude());
ListAddItem(isGps);
SendBroadcast();
locationManager.removeUpdates(this);
stopSelf();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public void onProviderEnabled(String provider){
isGps=true;
}
#Override
public void onProviderDisabled(String provider){
isGps=false;
lat=0.0;
lng=0.0;
mList.clear();
ListAddItem(isGps);
//SendBroadcast();
}
You should use a Service and a BroadcastReceiver

Fetch first location on android and stop updates

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 */

Categories

Resources