I need your help.
I have a activity that get every 5 min the current lat lon gps = new GpsData(StartActivity.this);. That works fine! But when I left a county and the activity refresh. Then I do not get the current lon lat. I dont know why.
Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
btnShowLocation = (Button) findViewById(R.id.report_btn);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(StartActivity.this, ReportActivity.class);
startActivity(intent);
finish();
}
});
}
#Override
public void onResume() {
super.onResume();
autoUpdate = new Timer();
autoUpdate.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//start GPS
gps = new GpsData(StartActivity.this);
//start json download
new task().execute();
}
});
}
}, 0, 300000); // updates each 5 min
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(StartActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Status Update...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
//get Location Data
double latitude = gps.latitude;
double longitude = gps.longitude;
String mlat = String.valueOf(latitude);
String mlon = String.valueOf(longitude);
//if (gps.latitude != 0.0) {
JSONObject json = jsonFunctions.getJSONfromURL("http://myurl);
Here is my GpsData
public class GpsData extends Service implements LocationListener {
public GpsData(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
// Get the location manager
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
return null;
}
/* Request updates at startup */
protected void onStart() {
}
/* Remove the locationlistener updates when Activity is paused */
protected void onPause() {
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
time = location.getTime();
speed = location.getSpeed();
}
It is simple: I want every 5 min the current lat lon and refresh the List view with the current data from the current county... How can I do this?
Change this
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
to
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300000, 0, this);
Related
I'm looking a way to get distance travelled by the user. On purpose I try services like this
public class GPSService extends Service {
private LocationListener listener;
private LocationManager locationManager;
private List<Location> locationList = new ArrayList<>();
private float distancetracking = 0;
private int j = 0;
private float finaldist = 0;
String provider;
public IBinder onBind(Intent intent){
return null;
}
#SuppressLint("MissingPermission")
#Override
public void onCreate() {
super.onCreate();
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
locationList.add(location);
Intent i = new Intent("location_update");
while (j < locationList.size() - 1) {
Location loc1 = locationList.get(j);
Location loc2 = locationList.get(j + 1);
distancetracking += loc1.distanceTo(loc2);
j++;
}
Log.d("service", String.valueOf(distancetracking));
finaldist = distancetracking/1000;
i.putExtra("coordinates", finaldist);
sendBroadcast(i);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(provider,0,0,listener);
}
#Override
public void onDestroy() {
super.onDestroy();
if (locationManager != null){
locationManager.removeUpdates(listener);
}
locationList.clear();
}
}
But when my app goes in background the location didn't receive any location...I was aware of some limitation but actually I didn't understand what to do. I'have to do that on purpose to calculta CO2 from the distance travelled
I want to get user coordinate, the gps is on , I've asked for permission it has the permissions.
the location is set , I've my locations on other apps like google map but in my application , it doesn't work :
public boolean startService() {
try {
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
return false;
}
}
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)) {
startService();
}
public class FetchCordinates extends AsyncTask<String, Integer, String> {
AlertDialog.Builder a;
AlertDialog dialog;
public double lati = 0.0;
public double longi = 0.0;
public LocationManager mLocationManager;
public FetchCordinates.VeggsterLocationListener mVeggsterLocationListener;
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new FetchCordinates.VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
a = new AlertDialog.Builder(Admins.this);
a.setMessage("در حال به دست آوردن موقعیت جغرافیایی...");
a.setPositiveButton(("بیخیال"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
FetchCordinates.this.cancel(true);
}
});
dialog = a.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.RIGHT);
messageText.setTypeface(typeface);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
dialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
Log.v("this","got the location");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0 && !isCancelled()) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
it shows me the dialog for getting the location but it never get the current location .
What's wrong with my code ?
Please provide what you wrote in your Manifest.xml file. Maybe there is something wrong with the permissions.
You need
android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION
for API 5.0 or higher also:
android.hardware.location.gps
I'm trying to make a simple program to perform distance calculations that will be shown in listview. I use GPSTracker from androidhive, and calling latitude and longitude fo my List Activity
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled =false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context){
this.mContext = context;
getLocation();
}
public Location getLocation() {
try{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled&& !isNetworkEnabled){
//no network enable
}else {
this.canGetLocation = true;
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network","Network");
if(locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location == null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} catch (Exception e){
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
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 location) {
// TODO Auto-generated method stub
}
#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
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And My List Activity
public class Mobil extends ListFragment implements LocationListener{
GPSTracker gps;
private static final String url = "http://10.0.2.2/tambalban/car.php";
JSONArray tambalban = null;
ArrayList<HashMap<String, String>> listMobil = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new getJSONData().execute();
}
public class getJSONData extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromURL(url);
gps = new GPSTracker(getActivity()); // is it right calling from GPSTracker?
double lat_user = gps.getLatitude(); // get latitude, right?
double lng_user = gps.getLongitude();
System.out.println("lat_user : "+lat_user+""); // print in logcat return 0.00
System.out.println("lng_user : "+lng_user+"");// print in logcat return 0.00
try {
tambalban = json.getJSONArray(TAG_TAMBALBAN);
for (int i = 0; i < tambalban.length(); i++) {
JSONObject mtr = tambalban.getJSONObject(i);
String id_tb = mtr.getString(TAG_ID);
String name_tb = mtr.getString(TAG_NAMA);
String address_tb = mtr.getString(TAG_ALAMAT);
String telp_tb = mtr.getString(TAG_TELP);
String lat = mtr.getString(TAG_LAT);
String lng = mtr.getString(TAG_LNG);
double lat_tujuan = Double.parseDouble(lat);
double lng_tujuan = Double.parseDouble(lng);
double distance = hitungJarak(lat_user, lng_user, lat_tujuan, lng_tujuan);
distance = RoundDecimal(distance, 2);
String dist = Double.toString(distance)+" km";
HashMap<String, String> a = new HashMap<String, String>();
a.put(TAG_ID, id_tb);
a.put(TAG_NAMA, name_tb);
a.put(TAG_ALAMAT, address_tb);
a.put(TAG_TELP, telp_tb);
a.put(TAG_LAT, lat);
a.put(TAG_LNG, lng);
a.put(TAG_JARAK, dist);
listMobil.add(a);
}
} catch (JSONException e) {
e.printStackTrace();
}
return listMobil;
}
private double RoundDecimal(double distance, int i) {
BigDecimal bd = new BigDecimal(distance);
bd = bd.setScale(i, 6);
return bd.doubleValue();
}
private double hitungJarak(double lat_user, double lng_user,
double lat_tujuan, double lng_tujuan) {
double dist;
double radius = 6371;
double dLat = Math.toRadians(lat_tujuan - lat_user);
double dLon = Math.toRadians(lng_tujuan- lng_user);
double a = Math.sin(dLat/2) * Math.sin(dLat /2)
+ Math.cos(Math.toRadians(lat_user)) * Math.cos(Math.toRadians(lat_tujuan))
* Math.sin(dLon/ 2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = radius * c;
double km = valueResult/1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
dist = radius * c;
return dist;
}
#Override
protected void onPostExecute(
ArrayList<HashMap<String, String>> listMobil) {
// TODO Auto-generated method stub
super.onPostExecute(listMobil);
ListAdapter adapter = new SimpleAdapter(getActivity(), listMobil,
R.layout.list_item, new String[] { TAG_NAMA, TAG_ALAMAT, TAG_JARAK },
new int[] { R.id.namatb, R.id.alamattb,R.id.jarak });
setListAdapter(adapter);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.list_fragment, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String pilih = getListAdapter().getItem(position).toString();
Toast.makeText(getActivity(),
pilih,
Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(), DetailDaftar.class);
Bundle bundle = new Bundle();
bundle.putString("Selected", pilih);
i.putExtras(bundle);
startActivity(i);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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 check using Sytem.out.println, both latitude and longitude return 0.00.
Am I wrong with calling current Location? Thanks you for any help.
You should create your GPSTracker gps object outside your AsyncTask try like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gps = new GPSTracker(getActivity()); // is it right calling from GPSTracker?
new getJSONData().execute();
}
And also add required permission into your manifest.xml file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
your GPSTracker class will return current location latitude and longitude. I have already checked and it is returning lat/long values.
In second part I am not getting, what you are trying to do with json but if you want to get latitude longitude in another activity then simply instantiate GPSTracker class like
Inside activity
GPSTracker tracker;
and inside onCreate method
tracker=new GPSTracker(this);
and another one thing ypu can not print or log any statement in doInBackground() method because it will run in background only.
Try to toast your output in onPostExecute() method
If you are using emulator for testing, then you should do the following:
1.In your editor (I assume you are using Eclipse) go to
Window -> Open Perspective -> Show View -> Emulator Control.
2 There you would see two editable textbox with tags 'latitude' and 'longitude'.
3 Set the values appropriately and click send.
Now your emulator has the values set by you.
This is my code for getting Longitude and Latitude , it works great for me
public void setLocation() {
LocationManager LM;
LM = (LocationManager) CurrentContext
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// adjust ur criteria with ur desired features
provider = LM.getBestProvider(criteria, true);
try {
LM.requestLocationUpdates(provider, 1000, 1, this);
if (LM != null) {
Loc = LM.getLastKnownLocation(provider);
if (Loc != null) {
userLocation = new Location("");
userLocation.setLatitude(Loc.getLatitude());
userLocation.setLongitude(Loc.getLongitude());
}
}
} catch (Exception e) {
DisplayUnexpected();
e.printStackTrace();
return;
}
LM.removeUpdates(this);
}
Use this code
public class LocationUpdateService extends Service {
private LocationManager _locationManager;
private boolean _gpsEnabled,_networkEnabled;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
_gpsEnabled = _locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
_networkEnabled = _locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void onStart(Intent intent, int startId) {
Log.e("onStart","onStart");
if( _gpsEnabled ) {
_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000, 0, locationListener);
} else if ( _networkEnabled ){
_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000, 0, locationListener);
}
};
LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
final Location currentLocation = location;
Log.e("onLocationChanged", " " + currentLocation);
_locationManager.removeUpdates(locationListener);
Toast.makeText(LocationUpdateService_2.this, "Location lat "+currentLocation.getLatitude()+ " long "+currentLocation.getLongitude() , Toast.LENGTH_LONG).show();
}
};
What am i trying to do is to get the GPS location from 2 providers, the first one is the GPS which is the most accurate, the second one is the aGPS which is a combination of GPS and network. I am doing that because aGPS can get location even in tall buildings when normal gps takes more time to get.
What i want is to try getting location from the first provider(GPS) for 10 seconds, if in those 10 seconds i get a location!=null, i break the timed loop and take the result to the main thread, which is the main activity. ELSE ill take the location from the second provider(aGPS) if available. If none of the provider where able to get a location, i will return null after the 10 seconds.
The problem i am facing is, when i do a timed loop, the app freezes for 10 seconds so im not able to get the location to the main activity.
Here i am trying to get the location on the HomeActivity class that extends Activity:
Button btnRedCross = (Button) this.findViewById(R.id.btnRedCross);
btnRedCross.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
OutRequestsDatabaseHandler db =new OutRequestsDatabaseHandler();
OutRequest outreq = new OutRequest();
outreq.setName("Red Cross");
//TODO get the message from LocalUser db
Calendar cal = Calendar.getInstance();
outreq.setDate(cal.getTimeInMillis());
outreq.setMessage("My Message");
outreq.setType("RedCross");
//outreq.setLongitude(12.123456);
//outreq.setLatitude(12.123456);
db.addOutRequest(HomeActivity.this, outreq);
//HERE I AM TRYING TO GET THE LOCATION
GPSTracker locationtracker=new GPSTracker(HomeActivity.this);
location=locationtracker.getLocation();
Log.i("LocationGetter","Result: Longitude:"+location[0]+" Latitude:"+location[1]);
}
});
}
This is the GPSTracker Class where the 2 providers try to get location:
public class GPSTracker{
Context con;
LocationManager locMgr;
private double longgps;
private double latgps;
private double longnetwork;
private double latnetwork;
private LocationListener gpsLocationListener;
private LocationListener networkLocationListener;
public GPSTracker(final Context context){
con = context;
locMgr = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
LocationProvider high = locMgr.getProvider(locMgr.getBestProvider(
createFineCriteria(), true));
LocationProvider low = locMgr.getProvider(locMgr.getBestProvider(
createCoarseCriteria(), true));
//GET LOCATION FROM GPS
gpsLocationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder
.setMessage(
"Please Enable GPS and Network For Accurate Result")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public void onLocationChanged(Location location) {
longgps = location.getLongitude();
latgps = location.getLatitude();
//Log.i("LocationGetter", "GPS: Longitude:" + longgps+ " Latitude:" + latgps);
}
};
locMgr.requestLocationUpdates(high.getName(), 0, 0f,gpsLocationListener);
//GET LOCATION FROM GPS + NETWORK
networkLocationListener=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 location) {
longnetwork = location.getLongitude();
latnetwork = location.getLatitude();
//Log.i("LocationGetter", "Network: Longitude:"+ longnetwork + " Latitude:" + latnetwork);
}
};
locMgr.requestLocationUpdates(low.getName(), 0, 0f,networkLocationListener);
}
public static Criteria createFineCriteria() {
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
return c;
}
public static Criteria createCoarseCriteria() {
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
return c;
}
public double[] getLocation() {
double location[] = new double[2];
Calendar cal = Calendar.getInstance();
Long endtime = cal.getTimeInMillis() + 10000;
while (Calendar.getInstance().getTimeInMillis() < endtime) {
if (longgps != 0 && latgps != 0) {
location[0] = longgps;
location[1] = latgps;
Log.i("LocationGetter", "GPS: Longitude:" + location[0]
+ " Latitude:" + location[1]);
break;
} else if (longnetwork != 0 && latnetwork != 0) {
location[0] = longnetwork;
location[1] = latnetwork;
Log.i("LocationGetter", "Network: Longitude:" + location[0]
+ " Latitude:" + location[1]);
}
}
locMgr.removeUpdates(networkLocationListener);
locMgr.removeUpdates(gpsLocationListener);
networkLocationListener = null;
gpsLocationListener = null;
return location;
}
}
Isn't this just a multithreading problem. Instead of doing the work on the main thread, one could create a second thread so that it doesn't matter if that thread is idle for 10 seconds.
Incidentally, instead of relying on any single provider, I think it's better to use all providers and trust them according to their accuracy using a Kalman filter. See my answer here for a simple Kalman filter that seems to work in the context of Android location providers.
Make your GPSTracker class abstract by declaring the method updatedLocation(Location loc) without body. In code
public abstract class GPSTracker{
.......
private Location mLocation;
public void updateLocation(Location loc);
private CountDownTimer mNetworkCountDown = new CountDownTimer(10000, 10000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
// this onFinish() will be called if not cancel by Gps
locMgr.removeUpdates(networkLocationListener);
updateLocation(mLocation);
}
};
private CountDownTimer mGpsCountDown = new CountDownTimer(10000, 10000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
locMgr.removeUpdates(gpsLocationListener);
}
};
.........
gpsLocationListener = new LocationListener() {
..........
#Override
public void onLocationChanged(Location location) {
// Get a gps fix cancel both countdowns and listeners
mGpsCountDown.cancel();
mNetworkCountDown.cancel();
locMgr.removeUpdates(gpsLocationListener);
locMgr.removeUpdates(networkLocationListener);
// The calling class will get the fix
updateLocation(location);
longgps = location.getLongitude();
latgps = location.getLatitude();
//Log.i("LocationGetter", "GPS: Longitude:" + longgps+ " Latitude:" + latgps);
}
};
locMgr.requestLocationUpdates(high.getName(), 0, 0f,gpsLocationListener);
mGpsCountDown.start();
.......
networkLocationListener=new LocationListener() {
..........
#Override
public void onLocationChanged(Location location) {
// No cancelation here, Gps will cancel if it gets a fix
mLocation = location;
longnetwork = location.getLongitude();
latnetwork = location.getLatitude();
//Log.i("LocationGetter", "Network: Longitude:"+ longnetwork + " Latitude:" + latnetwork);
}
};
locMgr.requestLocationUpdates(low.getName(), 0, 0f,networkLocationListener);
mNetworkCountDown.start();
.........
// remove the getLocation()
}
In HomeActivity class create a class that extends GPSTracker
public class HomeActivity extends Activity {
.........
public class MyGPSTracker extends GPSTracker
{
public void updateLocation(Location location)
{
// location would be null if both Gps and Network did not
// get a fix in 10 seconds
if (location != null)
{
// do whatever you want with this location fix
// If you want to know if this fix is from GPS or Network
// just use String provider = location.getProvider()
Log.i("LocationGetter","Result: Longitude:"+location.getLongitude()+" Latitude:"+location.getLatitude);
}
}
}
Button btnRedCross = (Button) this.findViewById(R.id.btnRedCross);
btnRedCross.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
OutRequestsDatabaseHandler db =new OutRequestsDatabaseHandler();
OutRequest outreq = new OutRequest();
outreq.setName("Red Cross");
//TODO get the message from LocalUser db
Calendar cal = Calendar.getInstance();
outreq.setDate(cal.getTimeInMillis());
outreq.setMessage("My Message");
outreq.setType("RedCross");
//outreq.setLongitude(12.123456);
//outreq.setLatitude(12.123456);
db.addOutRequest(HomeActivity.this, outreq);
//HERE I AM TRYING TO GET THE LOCATION
GPSTracker locationtracker=new MyGPSTracker(HomeActivity.this);
// You will get the location when updateLocation is called by the
// MyGPSTracker class
Log.i("LocationGetter","Result: Longitude:"+location[0]+" Latitude:"+location[1]);
}
});
}
I am using this link for location service and it works
Now I want to create BackgroundService that make calls to a function that gets location after every 5 minutes.
I think I need to use Timer for this, please tell me how to manage this 5 minutes gap in between this location class gets called.
public class LocationService extends Service {
private Timer timer;
private long UPDATE_INTERVAL ;
public static final String Stub = null;
LocationManager mlocmag;
LocationListener mlocList ;
private double lat,longn;
#Override
public void onCreate() {
super.onCreate();
webService = new WebService();
mlocmag = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocList = new MyLocationList();
Location loc = mlocmag.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc == null) {
loc = mlocmag.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
timer = new Timer(); // location.
UpdateWithNewLocation(loc); // This method is used to get updated
mlocmag.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocList);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
}
mlocmag.removeUpdates(mlocList);
}
#Override
public boolean stopService(Intent name) {
return super.stopService(name);
}
private void UpdateWithNewLocation(final Location loc) {
final SharedPreferences prefs = getSharedPreferences(Const.COMMON_SHARED, Context.MODE_PRIVATE);
userId = prefs.getString(Const.COMMON_USERID, null);
gps = prefs.getInt(Const.COMMON_GPS, 0);
UPDATE_INTERVAL = 500000;
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (loc != null) {
final double latitude = loc.getLatitude(); // Updated lat
final double longitude = loc.getLongitude(); // Updated long
String response = null ;
if (lat != latitude || longn != longitude ) {
response = webService.updateLatandLong(userId, latitude, longitude);
lat = latitude;
longn = longitude;
}
}
else {
String latLongStr = "No lat and longitude found";
}
}
}, 0, UPDATE_INTERVAL);
}
public class MyLocationList implements LocationListener {
public void onLocationChanged(Location arg0) {
UpdateWithNewLocation(arg0);
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS Disable ",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS enabled",
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
use This:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
//your code to get lat long
}
}, 0, 500000);