How to get user's GPS coordinates by clicking a button - android

i want to make application like this :
User clicks the button
The application show the user's coordinates (Latitude and Longitude)
i'm following the steps here
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
double glat = location.getLatitude();
double glong = location.getLongitude();
Toast.makeText(getApplicationContext(), "Your position\n"+glat+"\n"+glong, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
how to implement it to button click event?
if the user clicks the button, the toast appear showing the position :)
UPDATE
I implement it using startActivityForResult() but the result is empty or null
here's my code :
this is the code on the button that i want to click
btn_obj_useKor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), MyLocationListener.class);
startActivityForResult(intent, 0);
}
});
and this is my MyLocationListener class :
public class MyLocationListener extends Activity{
Intent intent;
String output = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double glat = location.getLatitude();
double glong = location.getLongitude();
output = glat+","+glong;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
intent.putExtra("returnedData", output);
setResult(RESULT_OK, intent);
finish();
}
}
When i click the button it showing WTF! that means the result is null or empty.
what's the problem and what should i do then?

It wont return a result immediately since it takes time for the GPS provider to start and find your location. This is why you listen for a callback event.
Currently your code is listening for the network location, which is not very accurate. Change the LocationManager to GPS_Provider (on your last line) to use GPS if it is enabled.

Responding to an onClick is a user event, the LocationListener onLocationChanged is also an event. If you trigger the user event before the LocationListener event, there will be no position available to display.
My suggestion is to call startActivityForResult on another activity in the button onClick handler, the 2nd activity has all the LocationManager & LocationListener code in it, in the onLocationChanged event handler you pass the position back to the 1st activity.

Related

Get GPS location in AsyncTask

I have an AsyncTask class that needs to get user's location when this AsyncTask is called.
The idea is to check if location service is enabled or not, if not, the location service toggle will popup for user to turn it on, then it will go back to the task to continue getting the location and finish the job.
However, the code below show NullPointerException on the line lat = location.getLatitude(); near the end of onPreExecute(). They said because getLastKnownLocation gets nothing as it's just been turned on a moment ago, then how can I get the location right after the location service has been turned on?
LocationManager locationManager;
LocationListener locationListener;
double lat;
double longi;
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
location = new Location(LocationManager.NETWORK_PROVIDER);
locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
//I copy the part below from the internet but seems like "onProviderDisabled" and "onLocationChanged" were never be called
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.v("GPS CHECKKKKKKK",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) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
};
locationManager.requestLocationUpdates("gps", 500, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,0, locationListener);
lat = location.getLatitude();
longi= location.getLongitude();
Log.v("GPS Cord CHECK",lat+"_"+longi);
}
#Override
protected String doInBackground(final Checkout_Package... params) {
//Doing the job that needs lat and longi value!
}
Thank you for your time!
You cannot create and put a location listener in onPreExecute() because the onChanged handlers will only be invoked much later when onPostExecute or even your AsyncTask has finished.
What you should do instead is start an AsyncTask in that location changed handler.
So in onLocationChanged().
With greenapps's suggest I figured it out. I put the code into the button that call the AsyncTask
checkout_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocationManager locationManager;
LocationListener locationListener;
gotit = false; //Boolean to start the AsyncTask only once.
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.v("GPS CHECKKKKKKK",location.getLatitude()+"_"+location.getLongitude());
lat = location.getLatitude();
longi = location.getLongitude();
if (gotit == false) {
new Checkout_Async(Checkout.this, listener).execute(new Checkout_Package(user, product_all, getTotalCost(product_all), fee, getTotalCost(product_all) + fee, lat, longi));
gotit = true;
pd.dismiss();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
pd=ProgressDialog.show(Checkout.this,"",getResources().getString(R.string.please_wait),false);
locationManager.requestLocationUpdates("gps",50,0,locationListener);
}
});
Now it works. Thank you!

How to get initial location with LocationManager?

I've been getting current location with GoogleApiClient up until now but I've just noticed that it's much simpler to do it with LocationManager using LocationListener since it can even detect when GPS service was turned on or off by the user.
But I have a problem when getting user's first location after the LocationManager was initialized.
LocationManager has 4 listeners but none of them give you your first location. It does have a onLocationChanged listener but it only activates when you move.
This is how I'm using it:
// Init LocationManager (needed to track if GPS is turned on or not
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
end of oncreate......
/*
LocationListener (Listening if GPS service is turned on/off)
*/
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderDisabled(String provider) {
}

How can i locate a postion in map for my application uses?

how i should locate a position in map ?
ok , so i want to locate my gate position in the park and to call the gate automaticly when i am about 50 meters far away from the position of the gate, i think i may start with determine the position of the gate in maps by google-maps or gps
but i dont realy know how
i tried to see some samples of google maps api , but i cant make it work for some reason .
anyway this should be an app in the end .. and i hope some of you guys will help me in some way
This is the basic you need, you get your latitude and longitude from this, and then you start a new activity by sending "geo:lat,lon" to intent, and that opens your google maps app. And this is a way you could find your current location. You should read more about LocationListener etc on the android developer website.
public class GetLocation extends Activity {
LocationManager lm;
LocationListener ll;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_location);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
try {
double latitude = getLatitude();
double longitude = getLongitude();
Uri uri = Uri.parse("geo:"+latitude+","+longitude);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
finish();
} catch(Exception e) {
System.out.println("ERROR: "+e);
}
}
}
#Override
protected void onStop() {
super.onStop();
lm.removeUpdates(ll);
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc){
loc.getLatitude();
loc.getLongitude();
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}

Stop LocationManager Updates

I'm trying to have GPS coordinates sent to a text message. This code works, but every time the GPS updates location, it tries to send a new text message. I can't figure out how to stop the location updates. This is what I have currently...I realize it may not be the most efficient way to do it.
Any help would be appreciated!
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
public void GPSDisable() {
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.removeUpdates(mlocListener);
}
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", "5555555555");
smsIntent.putExtra("sms_body", "Location:"+latitude+","+longitude);
GPSDisable();
startActivity(smsIntent);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#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 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 would set two global variables latitude and longitude.
This variables would be updated every onLocationChanged. You cannot change this comportament, but you can get out from there the sending of sms.
I would send the sms on a timer after 5 seconds let's say.
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", "5555555555");
smsIntent.putExtra("sms_body", "Location:"+latitude+","+longitude);
startActivity(smsIntent);
}
},
5000 );
And your onlocation changed could look like this
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
First I would advise you to have a look at this article.
Having said this, generally you should "unsubscribe" from the location manager when you do not need any more updates. Typically, you subscribe for location updates in "onCreate" and unsubscribe in "onDestroy" when you need updates for as long as your Activity is 'alive'.
Even better is to subscribe/unsubscribe when your activity is getting visible or hidden respectively (via "onResume"/"onPause" respectively). Have a look here for details on the Activity's lifecycle.
Now, about your specific problem, it is not clear what is your desired behavior. Do you want to send an SMS message every time the location changes? Or only when some time passes?
Assuming what you need is to send SMS whenever your location changes but not too often, I would suggest the following:
1. Register for location updates in "onResume" and unregister in "onPause".
2. Maintain some local variables that tell you which was the last time you sent an SMS message and what were the coordinates in it. These variables should probably persist Activity lifecycle events (e.g. when the Activity is destroyed, you should "store" these values, and restore them when you recreate it).
3. Whenever there is a new location update, check if it is too soon or too close (compared to the previous SMS) and if not send another message, updating the variables.
Having said these, please note that this will work for as long as your Activity is visible. If you need a similar functionality that does not require you to keep the Activity visible, I would suggest you use a BroadcastReceiver.

How to determine whether GPS position has been acquired on android?

Let's say I have a button which calls another activity only if the system knows the EXACT user's location. I made a dialog to ask the user to turn on GPS if it's disabled, but when the user enables GPS and pushes the button again, I will probably not have the exact location yet. Can anyone help me with this ?
You need to create a LocationListener, and wait for the callback. It is pretty well described in the api docs:
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// When you get here you have a location...
useTheNewLocationToEnableTheButton(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
You can listen for GpsStatus events, to make sure that user actually enabled GPS (GPS_EVENT_STARTED), and to be notified when GPS gets position fix (GPS_EVENT_FIRST_FIX).
If you don't know coordinates, the best way is to display a ProgressDialog while retrieving a location and, when you got it, dismiss ProgressDialog and launch your activity.
final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//here you can get coordinates via location.getLongitude() and
//location.getLatitude() methods, dismiss the progress dialog and
//start your activity
locationManager.removeUpdates(this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

Categories

Resources