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]);
}
});
}
Related
I have a simple class to get the current location of the user it was working with no problem.
after i add a new function before I start get the user current location to check if GPS is open or not, if not opened it take the user to the setting file to open the GPS and then start take his location now I wait very long time and no location comes out. here is the code i use to get the current Location.
SingleShotLocationProvider
public class SingleShotLocationProvider {
public static interface LocationCallback {
public void onNewLocationAvailable(GPSCoordinates location);
}
public static boolean GPSOpen = false;
public static boolean NetworkOpen = false;
// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
NetworkOpen = isNetworkEnabled;
if (isNetworkEnabled) {
Log.i("NETWORK_OPEN", "YES NETWORK Open");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
#Override public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override public void onProviderEnabled(String provider) { }
#Override public void onProviderDisabled(String provider) { }
}, null);
} else {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
GPSOpen = isGPSEnabled;
if (isGPSEnabled) {
Log.i("GPS_OPEN", "YES GPS Opened");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
#Override public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override public void onProviderEnabled(String provider) { }
#Override public void onProviderDisabled(String provider) { }
}, null);
}
else {
Toast.makeText(context, "Please Open GPS and retry", Toast.LENGTH_LONG).show();
MainWindow w = (MainWindow)context;
w.DisableTheProgressGPSClosed(); // i have a simple progress bar wait until the app get the location then it GONE
}
}
}
// consider returning Location instead of this dummy wrapper class
public static class GPSCoordinates {
public float longitude = -1;
public float latitude = -1;
public GPSCoordinates(float theLatitude, float theLongitude) {
longitude = theLongitude;
latitude = theLatitude;
}
public GPSCoordinates(double theLatitude, double theLongitude) {
longitude = (float) theLongitude;
latitude = (float) theLatitude;
}
}
}
here is the function I use to check the GPS open or not.
public boolean turnGPSOn()
{
LocationManager L = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!L.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "Please open GPS", Toast.LENGTH_LONG).show();
Intent I = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(I);
return true;
}
return false;
}
here how I use it when the user click the button.
public void GetLocation() {
if (turnGPSOn()) {
return;
}
Log.i("Process_GPS_DATA", "Done process now GPS");
progressBar.setVisibility(View.VISIBLE);
foo(this);
}
foo function which call the GPS class here.
public void foo(final Context context) {
// when you need location
// if inside activity context = this;
SingleShotLocationProvider.requestSingleUpdate(context,
new SingleShotLocationProvider.LocationCallback() {
#Override public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
Log.i("Location", "my location is " + location.latitude + "," + location.longitude);
String BaseLocation = "https://www.google.com/maps/?q=" + location.latitude + "," + location.longitude + "";
StartSendRequest(location.longitude, location.latitude, BaseLocation);
Log.i("Google_URL", BaseLocation);
}
});
}
the problem is everything works fine but I wait a long time and no location are show I don't know why this problem, when i make a test I close the android GPS and then make the test no location are provided I test the same class before add check part and it worked fine.
when i test in emulator with already open GPS it worked and give me a location when i close GPS and then test again it not worked and I wait for long time and nothing show so what I did wrong.
I am trying to get lat and lng and want to show that in a text box I want both mean Network address and GPS address so I have done this But every time I am getting only one address at a time
public class GetLocationMainActivity extends Activity {
double nlat;
double nlng;
double glat;
double glng;
LocationManager glocManager;
LocationListener glocListener;
LocationManager nlocManager;
LocationListener nlocListener;
TextView textViewNetLat;
TextView textViewNetLng;
TextView textViewGpsLat;
TextView textViewGpsLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_location_main);
//All textView
textViewNetLat = (TextView)findViewById(R.id.textViewNetLat);
textViewNetLng = (TextView)findViewById(R.id.textViewNetLng);
textViewGpsLat = (TextView)findViewById(R.id.textViewGpsLat);
textViewGpsLng = (TextView)findViewById(R.id.textViewGpsLng);
}
#Override
public void onDestroy() {
//Remove GPS location update
if(glocManager != null){
glocManager.removeUpdates(glocListener);
Log.d("ServiceForLatLng", "GPS Update Released");
}
//Remove Network location update
if(nlocManager != null){
nlocManager.removeUpdates(nlocListener);
Log.d("ServiceForLatLng", "Network Update Released");
}
super.onDestroy();
}
//This is for Lat lng which is determine by your wireless or mobile network
public class MyLocationListenerNetWork implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
nlat = loc.getLatitude();
nlng = loc.getLongitude();
//Setting the Network Lat, Lng into the textView
textViewNetLat.setText("Network Latitude: " + nlat);
textViewNetLng.setText("Network Longitude: " + nlng);
Log.d("LAT & LNG Network:", nlat + " " + nlng);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d("LOG", "Network is OFF!");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d("LOG", "Thanks for enabling Network !");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public class MyLocationListenerGPS implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
glat = loc.getLatitude();
glng = loc.getLongitude();
//Setting the GPS Lat, Lng into the textView
textViewGpsLat.setText("GPS Latitude: " + glat);
textViewGpsLng.setText("GPS Longitude: " + glng);
Log.d("LAT & LNG GPS:", glat + " " + glng);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d("LOG", "GPS is OFF!");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d("LOG", "Thanks for enabling GPS !");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public void showLoc(View v) {
//Location access ON or OFF checking
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
boolean networkWifiStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.NETWORK_PROVIDER);
//If GPS and Network location is not accessible show an alert and ask user to enable both
if(!gpsStatus || !networkWifiStatus)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(GetLocationMainActivity.this);
alertDialog.setTitle("Make your location accessible ...");
alertDialog.setMessage("Your Location is not accessible to us.To give attendance you have to enable it.");
alertDialog.setIcon(R.drawable.warning);
alertDialog.setNegativeButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
});
alertDialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Toast.makeText(getApplicationContext(), "Remember to give attandance you have to eanable it !", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
alertDialog.show();
}
//IF GPS and Network location is accessible
else
{
nlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
nlocListener = new MyLocationListenerNetWork();
nlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000 * 1, // 1 Sec
1, // 1 meter
nlocListener);
glocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
glocListener = new MyLocationListenerGPS();
glocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000 * 1, // 1 Sec
1, // 1 meter
glocListener);
}
}
}
Have you enable both NETWORK-LOCATION and GPS-LOCATION in Settings yet? As far as I know for Android ICS (4.x) and newer, due to the Security issue, you can't enable/disable location access programmatically. Try to test it on Android 2.x. Hope this helps.
You can use the new fused provider to get the user location quickly without confuse.
Location issues has been simplified with the new Google Play Services such as choosing best provider automatically depending on your priority.
Here is an example request;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(20000) // 20 seconds
.setFastestInterval(16) // 16ms = 60fps
.setNumUpdates(4)
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
Make sure you updated the Google Play Services in the SDK Manager and check out this link to get info about how to get users location with the new Play Services.
http://developer.android.com/training/location/retrieve-current.html
hi there can anybody give me a sample code for get location for every five minutes please i have tried and i can get location once by cliking on button,
but i need it to be displayed once for five minutes.
thank you
this is my code :
public void checkLocation(View v) {
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS is disabled.", Toast.LENGTH_SHORT).show();
} else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 15000, 1, this);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
Here is the code for getting location and set the listener for gps to get current location on few minute and distance, also I have used runnable object to get the location on every few minutes.
Location gpslocation = null;
private static final int GPS_TIME_INTERVAL = 60000; // get gps location every 1 min
private static final int GPS_DISTANCE= 1000; // set the distance value in meter
/*
for frequently getting current position then above object value set to 0 for both you will get continues location but it drown the battery
*/
private void obtainLocation(){
if(locMan==null)
locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(isLocationListener){
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,
GPS_TIME_INTERVAL, GPS_DISTANCE, GPSListener);
}
}
}
}
Now use this method to get the current location and the listener was called on location change with every 1 min and 1000 meter of distance.
For getting every 5 min you can use this handler and runnable to get this location on well set period time:
private static final int HANDLER_DELAY = 1000*60*5;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
myLocation = obtainLocation();
handler.postDelayed(this, HANDLER_DELAY);
}
}, START_HANDLER_DELAY);
Here is GPS listener for location change event:
private LocationListener GPSListener = new LocationListener(){
public void onLocationChanged(Location location) {
// update location
locMan.removeUpdates(GPSListener); // remove this listener
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
You can set interval time for listener and handler same for getting GPS location.
Hi Use the below timer code.
You can use the below options
option 1
this will get the locations if mobile moved 100meters.
captureFrequencey=3*60*1000;
LocationMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, captureFrequencey, 100, this);
have a look at this link http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates%28java.lang.String,%20long,%20float,%20android.location.LocationListener%29
Option 2
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
handler.sendEmptyMessage(0);
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000);
//=======================================================
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH:
//your code here
break;
default:
break;
}
}
};
Timer will call the handler for your time duration (change 1000 into your required time ).
Hope this will help you.
I used runnable for doing this,
final Runnable r = new Runnable() {
public void run() {
//Here add your code location listener call
handler.postDelayed(this, 300000 );
}
};
handler.postDelayed(r, 300000 );
try like this:
private Handler handler = new Handler();
handler.postDelayed(runnable, 300000);
private Runnable runnable = new Runnable() {
public void run() {
if (location != null) {
onLocationChanged(location);
} else {
System.out.println("Location not avilable");
}
handler.postDelayed(this, 300000);
}
};
I have application to get location from gps
but if GPS disabled my application getting force close
in emulator it's fine not error,but if run in device it's force close
how can i do this??
this is my code:
public class Track extends Activity implements LocationListener{
String curTime;
double lat;
double lng;
double alt;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final 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);
final String provider = locationManager.getBestProvider(criteria, true);
Dbhelper helper = new Dbhelper(this);
final SQLiteDatabase db = helper.getWritableDatabase();
updateWithNewLocation(null);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
db.isOpen();
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
//db.close();
}
}, 10*60*1000, 10*60*1000);
locationManager.requestLocationUpdates(provider, (10*60*1000), 10,
locationListener);
PackageManager manager = this.getPackageManager();
PackageInfo info = null;
try {
info = manager.getPackageInfo(this.getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(this,
"PackageName = " + info.packageName + "\nVersionCode = "
+ info.versionCode + "\nVersionName = "
+ info.versionName + "\nPermissions = "+info.permissions, Toast.LENGTH_SHORT).show();
System.out.println("PackageName = " + info.packageName + "\nVersionCode = "
+ info.versionCode + "\nVersionName = "
+ info.versionName + "\nPermissions = "+info.permissions);
}
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");
curTime = df.format(time);
lat = location.getLatitude();
lng = location.getLongitude();
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.schedule(new TimerTask(){
#Override
public void run(){
db.execSQL("INSERT INTO location (longitude,latitude,altitude,tgl_buat) VALUES " +
"('"+lng+"','"+lat+"','"+alt+"','"+curTime+"')");
db.close();
}
}, 10*60*1000, 10*60*1000);*/
}
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
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
}
}
please give me a solution..thank you for feed back :)
If you want to turn on GPS enabled automatically in your app, I'm afraid there is no way other than prompt the user.
You can achieve that easily with modifying onProviderDisabled() method in your LocationListener. The idea is to open a dialog asking user to turn on GPS:
public void onProviderDisabled(String arg0)
{
showDialog(CHOICE_GPS_ENABLE);
}
add in your activity:
protected final static int CHOICE_GPS_ENABLE = 1; //or any other number
#Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
switch (id)
{
case CHOICE_GPS_ENABLE:
dialog = createGPSEnableDialog();
break;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
protected Dialog createGPSEnableDialog()
{
Dialog toReturnGPS;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You don't have GPS enabled. Go to Settings and enable GPS?");
builder.setTitle("GPS failed");
builder.setPositiveButton("Yes, enable GPS",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
builder.setNegativeButton("No, quit application",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
onDestroy();
}
});
toReturnGPS = builder.create();
return toReturnGPS;
}
Hope it helps.
i want GPS turn on automatically if my application running
how can i do this??
I don't think you can do anything beyond prompt the user to turn it on. So Im afraid you are going to be unable to make your application work how you'd like.
use
Location locationtest;
public void onLocationChanged(Location location) {
locationtest=location;
updateWithNewLocation(locationtest);
}
public void onProviderDisabled(String provider){
locationtest= null;
updateWithNewLocation(locationtest);
}
instead of
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
When, I test this code on my android mobile phone the current location doesn't show up. Should I configure my mobile or increment new code into the code to allow it run on my mobile properly. A hint will be much appreciated. the code is as follows
public class GetLocation extends Activity {
TextView tv;
double latitude,longitude,accuracy;
private LocationManager lm;
private LocationListener lo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)this.findViewById(R.id.txtLocation);
lm=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
lo = new mylocationlistener();
tv.setText("waiting for location");
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
createGpsDisabledAlert();
}
}
//dialog to check if gps enabled or not
private void createGpsDisabledAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS is disabled! Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
showGpsOptions();
}
});
builder.setNegativeButton("Do nothing",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
}); //close negative builder
AlertDialog alert = builder.create();
alert.show();
}
private void showGpsOptions(){
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
private class mylocationlistener implements LocationListener {
public void onLocationChanged(Location location) {
if (location !=null){
longitude = location.getLongitude();
latitude = location.getLatitude();
accuracy = location.getAccuracy();
/*
Log.d("LOCATION CHANGED", latitude + "");
Log.d("LOCATION CHANGED", longitude + "");
*/ String str = "\n CurrentLocation: "+
"\n Latitude: "+ latitude +
"\n Longitude: " + longitude +
"\n Accuracy: " + accuracy;
Toast.makeText(GetLocation.this,str,Toast.LENGTH_LONG).show();
tv.append(str);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(GetLocation.this,"Error onProviderDisabled",Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(GetLocation.this,"onProviderEnabled",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(GetLocation.this,"onStatusChanged",Toast.LENGTH_LONG).show();
}
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void onResume(){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, lo);
super.onResume();
}
}
In your onCreate you need to call lm.requestLocationUpdates() to get your location listener working . See Requesting Location Updates