GPS location never aquired - android

I am trying to get the GPS location in android, and run an ASYNC task with the gps coordinates. My location class is not just stalling the app with gps on. I am not getting a gps coordinate back.
My activity which tries to get the gps location is:
public class FindBrewery extends ActionbarMenu {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beer_location_list);
String title = "Nearby Breweries";
TextView topTitle = (TextView) findViewById(R.id.beerLocationTitle);
topTitle.setText(title);
//get user location
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
///new code
LocationManager mlocManager=null;
LocationListener mlocListener;
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if(MyLocationListener.latitude>0)
{
double longitude = MyLocationListener.latitude;
double latitude = MyLocationListener.longitude;
Toast.makeText(getApplicationContext(), "inside gps if", Toast.LENGTH_LONG).show();
//get gps results
//construct url
String url = "myURL";
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
else
{
//not sure what to put here yet...
}
} else {
Toast.makeText(getApplicationContext(), "GPS is Not Turned on", Toast.LENGTH_LONG).show();
}
}
//new code end
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
}
MyLocationListener Class:
package com.example.beerportfoliopro;
/**
* Created by Mike on 11/26/13.
*/
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude=loc.getLatitude();
longitude=loc.getLongitude();
}
#Override
public void onProviderDisabled(String provider)
{
//print "Currently GPS is Disabled";
}
#Override
public void onProviderEnabled(String provider)
{
//print "GPS got Enabled";
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
I know it is getting stuck in MyLocationListenerClass because I am not getting to my toast at all.
Udate:
I tried adding getters to MyLocationListenerClass:
public double getLatitude(){
return latitude;
}
public double getLongitude(){
return longitude;
}
But when Igo back to my activity which calls all this I try:
double latitude = mlocListener.getLatitude();
Bt I get a cannot resolve method error on getLatitdue()

I think this is the problem:
you are calling the Class instead (MyLocationListener) of calling the instance of the class mlocListener
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if(MyLocationListener.latitude>0)
{
double longitude = MyLocationListener.latitude;
double latitude = MyLocationListener.longitude;
Toast.makeText(getApplicationContext(), "inside gps if", Toast.LENGTH_LONG).show();
//get gps results
//construct url
String url = "myURL";
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
try doing this :
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if(mlocListener.latitude>0)
{
double longitude = mlocListener.latitude;
double latitude = mlocListener.longitude;
Toast.makeText(getApplicationContext(), "inside gps if", Toast.LENGTH_LONG).show();
//get gps results
//construct url
String url = "myURL";
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
This should work

Related

GPS Location not get the data after add a function to check if gps is open or not

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.

How can I make automatic a process?

I make a tutorial of GPS that you can get the location pressing a button, but now I want to make this process automatically, I try calling it on the onCreate method but only works once.... any Idea how? this is what i try:
GPS CLASS
public class GPS implements LocationListener{
private final Context mContext;
//flag for GPS status
boolean isGPSEnable = false;
// Flag for network status
boolean isNetworkEnable = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; //location
double latitude; //latitude
double longitude; //longitude
// the minimum distances to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // Minimun distance 10 meters
// The minimum time between updates in millisenconds
private static final long MIN_TIME_BTW_UPDATES = 1000 * 60 * 1; // 1 MINUTE
// Declaring a Location Manager
protected LocationManager locationManager;
public GPS(Context context){
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
//getting GPS status
isGPSEnable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnable = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnable && !isNetworkEnable){
// no network provider is enable
}
else {
this.canGetLocation = true;
if(isNetworkEnable){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BTW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
Log.d("Network", "Network");
if(locationManager != null){
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enable get lat/long using GPS Services
if(isGPSEnable){
if(location == null){
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BTW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS ENABLE", "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((LocationListener) GPS.this);
}
}
/**
* function to get latitude
*/
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
//return latitude
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
//return longitude
return longitude;
}
/**
* Function to check GPS/wifi enable
* #return boolean
*/
public boolean canGetLocation(){
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will launch Settings Options
*/
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle(mContext.getString(R.string.AlertDialog_Tittle));
// Setting Dialog Message
alertDialog.setMessage(mContext.getString(R.string.dialog_message));
// On pressing Setting button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
}
});
// On pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
#Override
public void onLocationChanged(Location location){
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and the main-activity class:
public class MainActivity extends ActionBarActivity {
private EditText edTLatitud;
private EditText edTLongitud;
private EditText edTCompass;
private EditText edTDirecc;
private SensorManager sensorManager;
private Sensor compassSensor;
// GPS class
GPS gps;
// Compass class
Compass compass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gpsactivity);
edTCompass = (EditText)this.findViewById(R.id.edTxtBrujula);
edTDirecc = (EditText)this.findViewById(R.id.edTxtBrujdireccion);
edTLatitud = (EditText)this.findViewById(R.id.edTxtLatitud);
edTLongitud = (EditText)this.findViewById(R.id.edTxtLongitud);
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
compassSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
gps = new GPS(MainActivity.this);
// Check if GPS is enable
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// Print on the screen the coordinates
UpdateGPSonScreen(latitude, longitude);
}
else {
// can't get location
// GPS or network is not enable
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
// Show the Latitude and longitude of the GPS on the application
public void UpdateGPSonScreen(double latitude, double longitude)
{
try{
edTLatitud.setText(String.valueOf(latitude));
edTLongitud.setText(String.valueOf(longitude));
}
catch (Exception e)
{
e.printStackTrace();
}
}
thanks in advance...
Do you want the EditText to be updated with the user location information intermittently? If so, you could create a thread that on intervals calls a function that retrieves the location data.
If the GPS class is not used anywhere else except in MainActivity make it as inner class of your Activity or Implement LocationListener in your Activity class itself to update your TextViews inside onLocationChanged method.
Put locationManger null check before you use it anywhere, there is no sense an to check for null after using it multiple times.
Your Class structure should be like
public class MainActivity extends ActionBarActivity{
// Define your text views to use them globally
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gpsactivity);
//find all your views
}
class GPS implements LocationListener{
//copy all your code here with required correction
#Override
public void onLocationChanged(Location location){
//get your latitude and longitude from location Object
// call same method to update your view
}
}
}
I have written whole code in stackoverflow editor only so make correction if any syntax error is found.

how to make my activity not stop working

import android.app.Activity;
public class LocationTracking extends Activity {
Button btnShowLocation;
Button refresh;
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_tracking);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
refresh = (Button) findViewById(R.id.refresh);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(LocationTracking.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
((TextView)findViewById(R.id.latitude)).setText(Double.toString(latitude));
((TextView)findViewById(R.id.longitude)).setText(Double.toString(longitude));
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((TextView)findViewById(R.id.latitude)).setText("");
((TextView)findViewById(R.id.longitude)).setText("");
}
});
}
}
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
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);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long 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/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#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;
}
}
i found this gps tracking activity on the net i tried it already and it works perfectly but i encountered a problem later on.when i start a new activity it stop on running what i want to do is for it not to stop even if i start i new activity example if someone is calling or im texting the gps tracking will still track my location where did i make my mistake?
use this code, registered the LocationManager in onchangeLocation() method.
public class NewLocationListener implements android.location.LocationListener {
private final static String TAG = "LocationListener";
private Context context = null;
private LocationManager locationManager = null;
private double latitude = 0.0;
private double longitude = 0.0;
/*public String newlatitude=null;
public String newlongitude=null;*/
private Location gpslocation=null;
public void setDefault() {
Log.v(TAG + ".setDefault", "GPS Co-ordinates initialised");
latitude = 0.0;
longitude = 0.0;
}
public NewLocationListener(Context ctx) {
Log.v(TAG + ".LocationListener", "LocationListener constructor called");
context = ctx;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
public void onProviderDisabled(String provider) {
Log.v(TAG + ".onProviderDisabled", "onProviderDisabled method called");
}
public void onProviderEnabled(String provider) {
Log.v(TAG + ".onProviderEnabled", "onProviderEnabled method called");
}
public void onLocationChanged(Location location) {
gpslocation=location;
Log.v(TAG + ".onLocationChanged", "onLocationChanged method called");
//Toast.makeText(context, "onLocationChanged called", Toast.LENGTH_SHORT).show();
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (gpslocation != null) {
setLocationCoordinates(gpslocation);
} else {
Log.v(TAG + ".onLocationChanged", "couldn't get gps using onLocationChange");
getLastKnownLocation();
}
}
public void setLocationCoordinates(Location location) {
try {
double latNew = (location.getLatitude());
double lonNew = (location.getLongitude());
if (latNew != 0.0 && lonNew != 0.0) {
Log.v(TAG + ".onLocationChanged", "New location co-ordinates are not 0");
/* setLatitude(latNew);
setLongitude(lonNew);*/
/*
* latitude = latNew; longitude = lonNew;
*/
String newlatitude=Double.toString(latNew);
String newlongitude=Double.toString(lonNew);
Log.v(TAG, "new latitude is" + newlatitude+" new longitude is" + newlongitude);
//Toast.makeText(context, "lat: " + newlatitude+" lon: " + newlongitude, Toast.LENGTH_SHORT).show();
} else {
//Toast.makeText(context, "we got 0.0 value ", Toast.LENGTH_SHORT).show();
Log.v(TAG + ".onLocationChanged", "we got 0.0 value ");
}
} catch (Exception e) {
Log.v(TAG + ".onLocationChanged.Exception", "Exception is " + e);
}
}
public void getLastKnownLocation() {
Location location = locationManager.getLastKnownLocation(getBestProvider());
gpslocation=location;
if (gpslocation != null) {
//Toast.makeText(context, "LastKnownLocation called", Toast.LENGTH_SHORT).show();
setLocationCoordinates(gpslocation);
} else {
//Toast.makeText(context, "couldn't get LastKnownLocation", Toast.LENGTH_SHORT).show();
Log.v(TAG + ".onLocationChanged","couldn't get gps using lastKnownLocation");
}
}
public String getBestProvider() {
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
String bestProvider = locationManager.getBestProvider(criteria, true);
return bestProvider;
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v(TAG + ".onStatusChanged", "onStatusChanged method called");
}
public double getLatitude() {
if (gpslocation != null) {
latitude = gpslocation.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (gpslocation != null) {
longitude = gpslocation.getLongitude();
}
return longitude;
}

how to get the current location latitude and longitude of android mobile device?

I have implemented sample application for get the current location latitude longitude.If i lunch my application in emulator and i am sending latitude and longitude from Emulator Controls at eclipse then i am getting current location latitude and longitude which from emulator controls.If i lunch the same application in real device then i am not able to get current location latitude and longitude
I have implemented code for get the current location latitude and longitude as follows:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 11, 11, mlocListener);
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
Log.v("11111","Latitude :"+loc.getLatitude());
Log.v("22222","Longitude :"+ loc.getLongitude());
}
}
From the above code i am not getting current location latitude and longitude in real android device.
How can i get current location latitude and longitude of real device?
please any body help me
GPS_PROVIDER does not work in bound place. So if gps_provider is enabled but you get null location you can replace provider from gps to NETWORK_PROVIDER.
prasad try this code ..by using this i am successfully getting lat long
private Location location = null;
private LocationManager locationManager = null;
locationManager = (LocationManager) context.getSystemService (Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
locationCritera.setAccuracy(Criteria.ACCURACY_FINE);
locationCritera.setAltitudeRequired(false);
locationCritera.setBearingRequired(false);
locationCritera.setCostAllowed(true);
locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT);
String providerName = locationManager.getBestProvider(locationCritera,
true);
location = locationManager.getLastKnownLocation(providerName);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
currentLocation = context.getSharedPreferences(PREFS_NAME, 0);
editor = currentLocation.edit();
}
public String getCurrentLatitude() {
try {
if (!currentLocation.getString("currentLatitude", "")
.equalsIgnoreCase(""))
return currentLocation.getString("currentLatitude", "");
else if (location.getLatitude() != 0.0)
return Double.toString(location.getLatitude());
else
return "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return "0.0";
}
public String getCurrentLongitude() {
try {
if (!currentLocation.getString("currentLongitude", "")
.equalsIgnoreCase(""))
return currentLocation.getString("currentLongitude", "");
else if (location.getLongitude() != 0.0)
return Double.toString(location.getLongitude());
else
return "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return "0.0";
}
are you trying on emulator or device. if you are trying in device then your device should have to be near window or in open place.
override these methods in your MyLocationListener. so that you can track your GPS status. check and see if you can get whats the problem
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
On a real device, you will have to be patient and wait for a fix from the satellites. This can take several minutes, even with a clear view of the sky.
For testing outside, you would be better advised to have a simple text box in your app, initialise it to something like "No GPS fix yet", then send a string comprised of the lat/long coordinates to it when the location changes.
Maybe this is more clear. I will change the conditional to something more efficient later if it is possible
double longitude = 0;
double latitude = 0;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null) {
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else {
Location location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
}
There are two types of location providers,
GPS Location Provider
Network Location Provider
package com.shir60bhushan.gpsLocation;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
This Link can help you for more information
http://androidtutorials60.blogspot.in/2013/09/gps-current-location-of-device.html

Fetch first location on android and stop updates

I still have problem with fetching first location on android. I am using Criteria like
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setSpeedRequired(true);
String provider = lm.getBestProvider(criteria, true);
if(provider!=null && provider.length()>0){
lm.requestLocationUpdates(provider, 0, 0, this);
}
I need to stop when first time get location like lm.removeUpdates(this);
Where to put that line of code ? In onLocationChanged ?
Yes. onLocationChanged will be called on each location update. If you want one only, you can remove it there.
public class GPSLocatorActivity extends Activity {
double current_lat, current_lng;
MapView mapView;
boolean flag = true;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1,
mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
current_lat = loc.getLatitude();
current_lng = loc.getLongitude();
if (flag == true) {
flag = false;
go(current_lat, current_lng);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled !!! Please Enable It.",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}/* End of Class MyLocationListener */
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
public void go(double c_lat, double c_lng) {
System.out.println("your current Lat :: " + c_lat);
System.out.println("your current Lng :: " + c_lng);
/*turn of gps now */
turnGPSOff();
}
private void turnGPSOff() {
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
}/* End of UseGps Activity */

Categories

Resources