Here, GPS takes half an hour or more (time) to get the current location coordinates.
How can I use GPS from GPS_SATELLITES and GPS _NETWORK_PROVIDERS
simultaneously in the same context and get the value of the recent
GPS?
public class ImageFile extends Activity{
LocationListener listner;
Location location;
LocationManager locationManager ;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 10 * 1; // 1 minute
#Override
protected void onCreate(final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.branchreport_layout);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listner = new MyLocationListner();
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGPSEnabled==false&&isNetworkEnabled==false)
{
showSettingsAlert();
}
if (isGPSEnabled)
{
progress = ProgressDialog.show(this, "GPS",
"Fetching latitude and longitude...", true);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,listner);
}
else if (isNetworkEnabled)
{
progress = ProgressDialog.show(this, "GPS",
"Fetching latitude and longitude...", true);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,listner);
}
public class MyLocationListner implements LocationListener {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
x = location.getLatitude();
y = location.getLongitude();
if((x!=0) && (y!=0))
{
progress.dismiss();
locationManager.removeUpdates(listner);
Geocoder gCoder = new Geocoder(ImageFile.this);
try {
addresses = gCoder.getFromLocation(x, y, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
Log.d("TestTag", "Locality: " + addresses.get(0).getLocality()+"getAddressLine"+addresses.get(0).getAddressLine(0)+",getAdminArea"+addresses.get(0).getAdminArea()+",getSubLocality"+addresses.get(0).getSubLocality());
}
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
// 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);
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
GPS is always slow, so i'll suggest to use Android Location API using Google Play Services.
Steps
First check for availability of Google Play Services by calling in onResume() of the Activity
Once play services are available on the device, build the GoogleApiClient.
Connect to google api client by calling mGoogleApiClient.connect() in onStart() method. By calling this, onConnectionFailed(), onConnected() and onConnectionSuspended() (GooglePlayServiceListeners) will be triggered depending upon the connection status.
Once google api is successfully connected, displayLocation() should be called in onConnected() method to get the current location.
This is how we build the GoogleApiClient
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
displayLocation()
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longitude);
} else {
lblLocation
.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
A perfect explanation of the above methods and steps can be found here .also check the official documentation
Related
In my code when layout loads it fetch gps coordinate .This is my sample code. It works fine if GPS is off. If i turn on the gps its not loading the gps coordinates . I need to get user gps coordinates when he turn on GPS. so what is the problem . where i need to change. Sorry for my English.
dialog = new ProgressDialog(FXPage.this);
dialog.show();
dialog.setMessage("Getting Coordinates");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 100000000,
1, this);
} else if (locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 100000000,
1, this);
}
else {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Enable Location", Toast.LENGTH_LONG).show();
}
protected void refresh() {
super.onResume();
this.recreate();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
dialog.show();
latitude = location.getLatitude();
longitude =location.getLongitude();
if (latitude != 0 && longitude != 0){
edittext6.setText(location.getLatitude()+","+location.getLongitude());
dialog.dismiss();
}
}
#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
}
GPS dosen't works under roof.
You can get Location updates from Network provider first if its available.
If N/A then only request it from GPS and start a CountDownTimer
Now after timer expires u can check if the location is still null then Alert user "unable to get location update" and stop the GPS location update request.
to Avoid all above trouble you may simply want to use FusedLocation Api which work better than the previous LocationApi.
check this link for FusedLocation api.
This part of your code seems to be really strange:
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
dialog.show();
latitude = location.getLatitude();
longitude =location.getLongitude();
if (latitude != 0 && longitude != 0){
edittext6.setText(location.getLatitude()+","+location.getLongitude());
dialog.dismiss();
}
}
Basically you are showing and then immediately dismissing a dialog. Maybe you should use a timer to dismiss the dialog after coordinates are shown.
Here are some good advices to get a single location update.
First of all check that the GPS is enabled, this will make your workflow more robust:
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
Then before asking the LocationManager for new location updates I would check if there is a good enough "last known location" (this obviously depends on the precision you need).
For example you can iterate through each location provider to find the most timely and accurate last known location as shown here:
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
if ((time > minTime && accuracy < bestAccuracy)) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
}
else if (time < minTime &&
bestAccuracy == Float.MAX_VALUE && time > bestTime){
bestResult = location;
bestTime = time;
}
}
}
If the last known location is not recent enough you may request a single location update using the fastest location provider available:
if (locationListener != null &&
(bestTime < maxTime || bestAccuracy > maxDistance)) {
IntentFilter locIntentFilter = new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION);
context.registerReceiver(singleUpdateReceiver, locIntentFilter);
locationManager.requestSingleUpdate(criteria, singleUpatePI);
}
Obviously you need to configure a BroadcastReceiver:
protected BroadcastReceiver singleUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(singleUpdateReceiver);
String key = LocationManager.KEY_LOCATION_CHANGED;
Location location = (Location)intent.getExtras().get(key);
if (locationListener != null && location != null)
locationListener.onLocationChanged(location);
locationManager.removeUpdates(singleUpatePI);
}
};
I am developing an app which asks users to enable the GPS if not on and then maps user location on Map. The problem I am facing is that after user enables the GPS from settings and presses back button, the Dialog box is shown saying "Location user location" but the app fails to get the longitude and latitude. Although if at this stage if I exit the app and start it again and access the same activity where the user location will be shown on map, then it works fine.
Following are the files used by me:
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // 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);
// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the 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 the 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) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
LocationActivity.java
public class LocationActivity extends Activity {
Button btnGPSShowLocation;
Button btnSendAddress;
Button find_rick;
TextView tvAddress;
private ProgressDialog pDialog;
int progressBarStatus=0;
boolean shouldExecuteOnResume;
Handler progressBarHandler = new Handler();
AppLocationService appLocationService;
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
//Google maps implementation
GoogleMap googleMap;
private static final String TAG = LocationActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_layout);
shouldExecuteOnResume=false;
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage("Locating your location");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setProgress(0);
pDialog.setMax(100);
progressBarStatus = 0;
createMapView();
btnShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
btnSendAddress = (Button) findViewById(R.id.btnSendAddress);
gps = new GPSTracker(LocationActivity.this);
// Check if GPS enabled and if enabled after popup then call same fn
Log.d("OnCreate","OnCreate");
MapMyCurrentLoction();
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MapMyCurrentLoction();
}
});
btnSendAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tag_string_req_send_data = "req_send";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_AUTOWALA_DHUNDO, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Autowala Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
} else {
// Error occurred in data sending. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Data sending Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "data_send");
params.put("latitude", Double.toString(gps.getLatitude()));
params.put("longitude", Double.toString(gps.getLongitude()));
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req_send_data);
}
});
}
#Override
protected void onPause(){
super.onPause();
}
#Override
protected void onResume(){
super.onResume();
if(shouldExecuteOnResume)
{
pDialog.show();
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
progressBarStatus = getULocation();
try {
Thread.sleep(7000);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBarHandler.post(new Runnable() {
public void run() {
pDialog.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
}
}).start();
//super.onResume();
}
else{
shouldExecuteOnResume=true;
}
/*pDialog.setMessage("Locating your location");
showDialog();*/
/*while(gps.getLatitude()==0.0 && gps.getLongitude()==0.0)
{
}*/
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
addMarker(latitude, longitude);
//super.onResume();
}
private int getULocation()
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Location location;
// The minimum distance to change Updates in meters
final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
boolean flag=gps.canGetLocation();
LocationManager locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
location=locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Getting GPS status
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(latitude > 0.0 && longitude > 0.0)
{
return 100;
}
else
{
return 0;
}
}
private void createMapView(){
/**
* Catch the null pointer exception that
* may be thrown when initialising the map
*/
try {
if(null == googleMap){
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.getUiSettings().setZoomGesturesEnabled(true);
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if(null == googleMap) {
Toast.makeText(getApplicationContext(),
"Error creating map",Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception){
Log.e("mapApp", exception.toString());
}
}
/**
* Adds a marker to the map
*/
private void addMarker(double lat,double lng){
/** Make sure that the map has been initialised **/
if(null != googleMap){
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat,lng))
.title("Your Location")
.draggable(true)
);
//zooming to my location
float zoomLevel = 16.0F; //This goes up to 21
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, zoomLevel);
googleMap.animateCamera(yourLocation);
}
}
private void MapMyCurrentLoction(){
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
addMarker(latitude,longitude);
/*------- To get city name from coordinates -------- */
String area = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addressList = null;
try {
addressList = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
area = sb.toString();
}
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude + "\n"+area, Toast.LENGTH_SHORT).show();
} else {
// Can't get location.
// GPS or network is not enabled.
// Ask user to enable GPS/network in settings.
gps.showSettingsAlert();
//Again search and map my location after enabling gps
}
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
When the app starts it's execution from onResume() method after user enables GPS from settings, even though isGPSEnabled returns true, I cannot get longitude or latitude and the dialog stays on screen until the app is closed.
I am new to Android Development so many of this things are a bit confusing to me at this stage so it will be very useful if I can get a solution for the problem as soon I can.
EDIT
Problem:
I am using AsyncTask now for my purpose and I have taken out the getLocation() method out of the constructor. However now the dialog "Searching GPS.." is shown continuously because of the while loop used in doInBackground() method I guess.
Here is my class which uses AsyncTask
private class InsertDataTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(LocationActivity.this);
#Override
protected Void doInBackground(Void... params) {
Log.d("Before getLocation=",String.valueOf(gps._isGPSEnabled));
gps.getLocation(LocationActivity.this);
Log.d("After getLocation=", String.valueOf(gps._isGPSEnabled));
while(gps.getLatitude()==0.0){
//do nothing
}
return null;
}
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Searching GPS...");
this.dialog.show();
}
// can use UI thread here
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
addMarker(gps.getLatitude(),gps.getLongitude());
}
}
Since ur calling getLocation() in constructor of GPS tracker class the method getLocation() gets executed only once (in this method only ur updating the status of the boolean canGetLocation) So when u execute the program without turning ON GPS it will update the status of canGetLocation to false and as ur saying when u turn it ON it will never update the status because u are not calling the method getLocation from ur Activity anywhere(like on a button click). Instead ur just checking the boolean value which is always false until u exit ur App and come back(until u create a new object;i.e calling the constructor). So dont call the method getLocation from constructor instead call it on a Button click, so the boolean value will get updated as u turn ON the GPS.
I have an app which calculates distance and speed by gps
the speed is working well
but the distance always equals to zero !!
at first i didn't initialize float[] dist by zero .. but it crashed once gps was found !
that's the code
public class Main_Activity extends Activity {
TextView tvdistance;
TextView tvSpeed;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance = 0;
float[] dist = {
0, 0, 0
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
tvdistance = (TextView) findViewById(R.id.tvdistance);
tvSpeed = (TextView) findViewById(R.id.tvspeed1);
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc == null) {
tvdistance.setText("No GPS location found");
}
else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
}
// Set the last latitude and longitude
lastLat = currentLat;
lastLon = currentLon;
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
// Get last location
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Request new location
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
if (currentLat != 0 && currentLon != 0) {
Location.distanceBetween(currentLat, currentLon, location.getLatitude(),
location.getLongitude(), dist);
distance += (long) dist[0];
}
currentLat = location.getLatitude();
currentLon = location.getLongitude();
float speed = location.getSpeed();
tvSpeed.setText("Speed = " + speed / 1000 * 60 * 60 + "Km/h");
tvdistance.setText("Distance = " + distance);
}
#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
}
};
}
As you have just gotten a location fix, I fully expect the location returned from getLastKnownLocation to be the same as what you get in location. This means that your distance between the two is correctly 0. If you want your older location, you'll need to store that yourself.
Here is the complete code to get location updates from a GPS provider
public class MainActivity extends Activity {
private GoogleMap googleMap;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1
// meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000; // 1
// second
// Declaring a Location Manager
protected LocationManager locationManager;
// The alert dialog to enable GPS
private Dialog alertDialog;
// flag for GPS status
boolean isGPSEnabled = false;
Location location; // location
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onStart()
*/
#Override
protected void onStart() {
// fetching your current location
super.onStart();
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
if (googleMap != null) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
}
// Getting current location and adding the marker
locateMe();
}
/**
*
*/
private void locateMe() {
// Checking for GPS Enabled
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
// GPS is disabled
askUserToEnableGPS();
}
}
/**
*
*/
private void askUserToEnableGPS() {
// Asking user to enable GPS
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog
// characteristics
builder.setMessage(R.string.generic_gps_not_found)
.setTitle(R.string.generic_gps_not_found_message_title)
.setPositiveButton(R.string.generic_yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected yes
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(R.string.generic_no,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected no
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onResume()
*/
#Override
protected void onResume() {
// Getting location from GPS
super.onResume();
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);
Log.e("GPS Enabled", "GPS Enabled");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// Setting the marker
if (googleMap == null || location == null) {
return;
} else {
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
location.getLatitude(), location.getLongitude())));
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 3000ms
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
}, 1000);
Marker myLocation = googleMap.addMarker(new MarkerOptions()
.position(
new LatLng(location.getLatitude(), location
.getLongitude()))
.title("Me")
.snippet("I am here")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
}
locationManager.removeUpdates(listener);
locationManager = null;
}
};
}
Now you can use various methods to store your location. Following are some ways:
Shared preferences
SQLite Database
Web Server
Saving in a file
You can refer this link.
i tried a lot of "get current location" for android. But i think most of them are outdated, or i simply dont get it.
I DONT want to set a marker.addmarker(params..) i would like to use the blue default dot for my position on Gmaps. Here i've found somthing about that, but for my bad it also aint work.
Customize marker of myLocation Google Maps v2 Android
So in first line i need, my current Location with a Listener when my Location is updating. Im trying this right now (Testing on a real device). But myLocation is always =null.
//get GMaps Fragment
mMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true); //activate Blue dot
myLocation = mMap.getMyLocation(); //Testing, but not working = null
//Trying with LocationManager
locManager =(LocationManager)getSystemService(this.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locManager.getBestProvider(criteria, true);
myLocation = locManager.getLastKnownLocation(provider);
if(myLocation != null){
double lat = myLocation.getLatitude();
double lon = myLocation.getLongitude();
}
locManager.requestLocationUpdates(provider, 1000, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
myLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
Follow this http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ . Then just place the latitude and longitude you get(using gps.getLatitude(), gps.getLongitude()) in your google map and it will show your current location.
Try this code, it is worked in my application:
private LocationManager locationManager;
private String provider;
double lat,lon;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locate);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 1, this);
if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
gpsalert();
}
// Criteria to select location provider
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Toast.makeText(getApplicationContext(), "Provider is available", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Provider is not available", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String addr,city,country;
lat=location.getLatitude();
lon=location.getLongitude();
//Toast.makeText(getApplicationContext(), "lat"+lat+"long"+lon, Toast.LENGTH_LONG).show();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lon, 1);
addr = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getAddressLine(1);
country = addresses.get(0).getAddressLine(2);
t1.setText(addr+"\n"+city+"\n"+country);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_SHORT).show();
//t1.setText("");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Enabled provider " + provider, Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
//locationManager.requestLocationUpdates(provider, 400, 1, this);
}
// Remove LocationListener updates
#Override
protected void onPause() {
super.onPause();
//locationManager.removeUpdates(this);
}
public void gpsalert()
{
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
This Google Maps v2 api confuses me quite a bit. I have implemented it now in some way i would like to use it. I just have two small problems that i don't know how to go about.
Sometimes I don't get a location when i start the app with gps enabled or it takes way too long to get one.
So I would like it to always load with the internet location provider first to have a very fast location fix as well as always using the getlastknownlocation() first. Cant figure out how to go about it.
Here my code:
public class MapViewMain extends FragmentActivity implements LocationListener, LocationSource
{
private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
final int RQS_GooglePlayServices = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mapviewmain);
//start power button service
Intent intent=new Intent("com.epicelements.spotnsave.START_SERVICE");
this.startService(intent);
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
Toast.makeText(this, "Google Service not found", Toast.LENGTH_LONG).show();
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locationManager != null)
{
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!gpsIsEnabled) {
// Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
PopIt("No GPS found", "Would you like to go to the settings to activate it?");
}
if(gpsIsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
}
else if(networkIsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000L, 10F, this);
}
else
{
//Show an error dialog that GPS is disabled...
}
}
else
{
//Show some generic error dialog because something must have gone wrong with location manager.
}
setUpMapIfNeeded();
}
}
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
locationManager.getBestProvider(criteria, true);
if(mListener != null){
}
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true); // Enable the my-location layer
if(locationManager != null)
{
mMap.setMyLocationEnabled(true); // Enable the my-location layer
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null)
{
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
{
setUpMap();
}
//This is how you register the LocationSource
mMap.setLocationSource(this);
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera.
* <p>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setPadding(0,60,0,150);
Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE);
}
#Override
public void activate(OnLocationChangedListener listener)
{
mListener = listener;
}
#Override
public void deactivate()
{
mListener = null;
}
#Override
public void onLocationChanged(Location location)
{
if( mListener != null )
{
mListener.onLocationChanged( location );
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
//save coordinate
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putFloat("lat", (float) location.getLatitude());
editor.putFloat("lng", (float) location.getLongitude());
editor.putFloat("accuracy", (float) location.getAccuracy());
editor.commit();
//marker stuff
mMap.clear();
mMap.addMarker(new MarkerOptions()
.position(coordinate)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 16));
}
}
#Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
// Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
// Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
// Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
// Alarm Dialog if GPS not enabled
public void PopIt( String title, String message ){
new AlertDialog.Builder(this)
.setTitle( title )
.setMessage( message )
.setCancelable(false)
.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//do stuff onclick of YES
//AlertDialog.dismiss();
}
})
.setNegativeButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//do stuff onclick of CANCEL
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
}
}
You can use LocationClient for your purpose its give LastLocation very fast.
first declare class variable
private LocationClient client;
after in onCreate
try {
if (map == null) {
MapsInitializer.initialize(this);
client = new LocationClient(this, new ConnectionCallbacks() {
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle connectionHint) {
// TODO Auto-generated method stub
Toast.makeText(MotoFreightHomeMapMainActivity.this,
"onConnected", Toast.LENGTH_LONG).show();
Location currentLocation = client.getLastLocation();
if (currentLocation != null) {
//do you stuff here
}
}
}, new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
});
client.connect();
}
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
etMap.setVisibility(View.INVISIBLE);
btnEditLocation.setVisibility(View.INVISIBLE);
Toast.makeText(this, "Please install Google Play Library",
Toast.LENGTH_SHORT).show();
}
see full code here
http://developer.android.com/training/location/retrieve-current.html
You can find a sample and tutorial from here.