Get GPS Location instantly via Android app - android

all. I am writing an android app about GPS locations.
I tried it on emulator and entered the latitude and longitude manually, and it worked fine.
However, my problem is: on the real device, in debugging mode, to go the next class by using intent can only be achieved when location is changed. If I start the app directly, I can see the blinking GPS icon, but the app will only stay here, and won't start the next activity. It seems that the variables in the onLocationChanged() will never be changed.
I have heard that to get the location instantly is to use the getLastKnownLocation() method. But I failed to get where I should use it.
Here is the class of how I use the LocationManager to get the locations.
Is there any solutions? I am quite confused. Thank you very much!!
public class mainMenu extends Activity{
private LocationManager locationManager = null;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent i3 = new Intent();
i3.setClass(mainMenu.this, police.class);
i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainMenu.this.startActivityForResult(i3,0);
}
});
Button button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent i3 = new Intent();
i3.setClass(mainMenu.this, ambulance.class);
i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainMenu.this.startActivityForResult(i3,0);
}
});
Button button3 = (Button)findViewById(R.id.button3);
button3.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent i3 = new Intent();
i3.setClass(mainMenu.this, fire_station.class);
i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainMenu.this.startActivityForResult(i3,0);
}
});
locationManager = (LocationManager)mainMenu.this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000 , 0, new MyLocationUpdater());
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
}
public class MyLocationUpdater implements LocationListener{ //change location interface
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// store the location data
// get the best record
Double lat = location.getLatitude();
Double lon = location.getLongitude();
System.out.println("The latitude is " + lat + "and "
+ "the longitude is "+ lon);
Double lat11 = lat - 1/69.0;
Double lat12 = lat + 1/69.0;
Double lon11 = lon - 1/42.0;
Double lon12 = lon + 1/42.0;
StaticVariables.latS1 = lat11.toString();
StaticVariables.latN1 = lat12.toString();
StaticVariables.lonW1 = lon11.toString();
StaticVariables.lonE1 = lon12.toString();
Double lat111 = lat - 2/69.0;
Double lat121 = lat + 2/69.0;
Double lon111 = lon - 2/42.0;
Double lon121 = lon + 2/42.0;
StaticVariables.latS11 = lat111.toString();
StaticVariables.latN11 = lat121.toString();
StaticVariables.lonW11 = lon111.toString();
StaticVariables.lonE11 = lon121.toString();
// ==================================================
// ambulances
Double lat21 = lat - 3/69.0;
Double lat22 = lat + 3/69.0;
Double lon21 = lon - 3/42.0;
Double lon22 = lon + 3/42.0;
StaticVariables.latS2 = lat21.toString();
StaticVariables.latN2 = lat22.toString();
StaticVariables.lonW2 = lon21.toString();
StaticVariables.lonE2 = lon22.toString();
Double lat211 = lat - 5.5/69.0;
Double lat221 = lat + 5.5/69.0;
Double lon211 = lon - 5.5/42.0;
Double lon221 = lon + 5.5/42.0;
StaticVariables.latS21 = lat211.toString();
StaticVariables.latN21 = lat221.toString();
StaticVariables.lonW21 = lon211.toString();
StaticVariables.lonE21 = lon221.toString();
// ===================================================
// fire stations
Double lat31 = lat - 2/69.0;
Double lat32 = lat + 2/69.0;
Double lon31 = lon - 2/42.0;
Double lon32 = lon + 2/42.0;
StaticVariables.latS3 = lat31.toString();
StaticVariables.latN3 = lat32.toString();
StaticVariables.lonW3 = lon31.toString();
StaticVariables.lonE3 = lon32.toString();
Double lat311 = lat - 2/69.0;
Double lat321 = lat + 2/69.0;
Double lon311 = lon - 2/42.0;
Double lon321 = lon + 2/42.0;
StaticVariables.latS31 = lat311.toString();
StaticVariables.latN31 = lat321.toString();
StaticVariables.lonW31 = lon311.toString();
StaticVariables.lonE31 = lon321.toString();
Intent intent = new Intent();
intent.setClass(mainMenu.this, getPhoneNumber.class);
mainMenu.this.startActivity(intent);
}
#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
}
}
}

The getLastKnownLocation method does not trigger an onLocationChanged event. One way to refactor your code would be to move the logic that acts on a Location to a separate method and then call that method both after you call getLastKnownLocation, and from your onLocationChanged method.
Bear in mind that there is no guarantee that getLastKnownLocation will provide a meaningful Location, since you the device might have moved since the last location update.
Example code:
public void onCreate(Bundle savedInstanceState){
....
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateLocation(location);
}
public class MyLocationUpdater implements LocationListener{ //change location interface
#Override
public void onLocationChanged(Location location) {
updateLocation(location);
}
...
}
void updateLocation(Location location) {
Double lat = location.getLatitude();
Double lon = location.getLongitude();
// the rest of the code from onLocationChanged
}

getLastKnownLocation() is faster after a connection has been established with the GPS satellite. For the first time, it will return null, or no value till no connection is established.
You can add a GpsListener to know when the location is obtained. Search about "how to get a gps fix" and you might get answer to your question

I have same problem before..but I have got the solution..this is the simplest way to get location instantly.
public class LocationFinder extends Activity {
TextView textView1;
Location currentLocation;
double currentLatitude,currentLongitude;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView) findViewById(R.id.textView1);
Log.i("########## Inside LocationFinder onCreate", "LocationFinder onCreate");
FindLocation();
}
public void FindLocation() {
LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
Toast.makeText(
LocationFinder.this,
String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 5000)
.show();
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
void updateLocation(Location location) {
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
textView1.setText(String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude));
}
}
Don't forget to Give permission in Manifeast.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>

public class HomeActivity extends Activity implements LocationListener{
public static Context mContext;
private double latitude, longitude;
public LocationManager mLocManager;
// *******This is the new Code start on 11/4/2011 at 3 o'clock
/**
* This is the Home Button if user Login then it is move to TennisAppActivity otherwise move to Login
*
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homelayout);
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
this);
mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, this);
locationUpdate();
((Button) this.findViewById(R.id.ButtonHome))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
DefaultDisplay.class));
}
});
((Button) this.findViewById(R.id.ButtonProfile))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
MyProfile.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","MyProfile");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonNotifications))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
ShowAllNotificationActiviry.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","ShowAllNotificationActiviry");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonFavorites))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
FavoritesActivity.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","FavoritesActivity");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonMore))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
MoreListActivity.class));
}
});
}
public void locationUpdate()
{
CellLocation.requestLocationUpdate();
}
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
GUIStatics.currentAddress = obj.getSubAdminArea() + ","
+ obj.getAdminArea();
GUIStatics.latitude = obj.getLatitude();
GUIStatics.longitude = obj.getLongitude();
GUIStatics.currentCity= obj.getSubAdminArea();
GUIStatics.currentState= obj.getAdminArea();
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
// Toast.makeText(this, "Address=>" + add,
// Toast.LENGTH_SHORT).show();
// TennisAppActivity.showDialog(add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
GUIStatics.latitude=location.getLatitude();
GUIStatics.longitude= location.getLongitude();
Log.v("Test", "IGA" + "Lat" + latitude + " Lng" + longitude);
//mLocManager.r
getAddress(latitude, longitude);
if(location!=null)
{
mLocManager.removeUpdates(this);
}
// Toast.makeText(this, "Lat" + latitude + " Lng" + longitude,
// Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
if(arg1 ==
LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
}
else if(arg1== LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show();
}
}
}
This is the code i have use it for finding the device location with the help of latitude and longitude and we also call getLastLocationUpdate in this code.
I hope this is very help full to you.

Related

0.0 value when data pass over from First Activity to Next(Android)

i wanted to pass my distance and duration over to the next page, but the result display is 0.0 for both
first Activity
btnStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
startButtonClicked=false;
startDistance=false;
Double value=Double.valueOf(distance.getText().toString());
Double durationValue=time;
Intent intent = new Intent(MainActivity.this, FinishActivity.class);
intent.putExtra("dist", value);
intent.putExtra("time",durationValue);
startActivity(intent);
finish();
}
});
at the Activity where it display
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finish);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
Double value = extras.getDouble("dist");
Double durationValue = extras.getDouble("time");
displayDistance=(TextView)findViewById(R.id.finishDistance);
displayDistance.setText("Distance: " + value);
displayDuration=(TextView)findViewById(R.id.finishDuration);
displayDuration.setText("Duration: " + durationValue);
}
the app crash after i presses stopped
here is my full Java code for the first Activity(second just display them). in case you all want to see how i get them
public class MainActivity extends FragmentActivity implements LocationListener{
protected LocationManager locationManager;
private GoogleMap googleMap;
Button btnStartMove,btnPause,btnResume,btnStop;
static double n=0;
Long s1,r1;
double dis=0.0;
Thread t1;
EditText userNumberInput;
boolean bool=false;
int count=0;
double speed = 1.6;
double lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4;
double dist = 0;
TextView distance;
Button btnDuration;
float[] result;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES =1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 4000; //in milliseconds
boolean startDistance = false;
boolean startButtonClicked = false;
MyCount counter;
int timer = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
if(isGooglePlay())
{
setUpMapIfNeeded();
}
distance=(TextView)findViewById(R.id.Distance);
btnDuration=(Button)findViewById(R.id.Duration);
btnStartMove=(Button)findViewById(R.id.Start);//start moving
btnStop=(Button)findViewById(R.id.Stop);
//prepare distance...........
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
btnStartMove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
lat3 = location.getLatitude();
lon3 = location.getLongitude();
startButtonClicked=true;
counter= new MyCount(30000,1000);
counter.start();
Toast.makeText(MainActivity.this,
"start is true",
Toast.LENGTH_LONG).show();
}
});
btnStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
startButtonClicked=false;
startDistance=false;
//String dis = (String) distance.getText();
//Double dd = Double.parseDouble(dis);
Intent intent = new Intent(MainActivity.this, FinishActivity.class);
//DecimalFormat df = new DecimalFormat("#.##");
//dist=(df.format(dd);
intent.putExtra("dist","value");
//intent.putExtra("speed","speedValue");
intent.putExtra("time","durationValue");
startActivity(intent);
finish();
}
});
btnDuration.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(startButtonClicked=true)
{
double time=n*30+r1;
Toast.makeText(MainActivity.this,"Speed(m/s) :"+String.valueOf(dist/time)+"Duration :"+String.valueOf(time),Toast.LENGTH_LONG).show();
}
}
});
if(location!= null)
{
//Display current location in Toast
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
//Display current location in textview
//latitude.setText("Current Latitude: " + String.valueOf(location.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(location.getLongitude()));
}
else if(location == null)
{
Toast.makeText(MainActivity.this,
"Location is null",
Toast.LENGTH_LONG).show();
}
}
private void setUpMapIfNeeded() {
if(googleMap == null)
{
Toast.makeText(MainActivity.this, "Getting map",
Toast.LENGTH_LONG).show();
googleMap =((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.displayMap)).getMap();
if(googleMap != null)
{
setUpMap();
}
}a
}
private void setUpMap()
{
//Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
//Get locationManager object from System Service LOCATION_SERVICE
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
if(provider == null)
{
onProviderDisabled(provider);
}
//set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Get current location
Location myLocation = locationManager.getLastKnownLocation(provider);
if(myLocation != null)
{
onLocationChanged(myLocation);
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
private boolean isGooglePlay()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS)
{
Toast.makeText(MainActivity.this, "Google Play Services is available",
Toast.LENGTH_LONG).show();
return(true);
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
}
return (false);
}
#Override
public void onLocationChanged(Location myLocation) {
System.out.println("speed " + myLocation.getSpeed());
//show location on map.................
//Get latitude of the current location
double latitude = myLocation.getLatitude();
//Get longitude of the current location
double longitude = myLocation.getLongitude();
//Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
//show distance............................
if(startDistance == true)
{
Toast.makeText(MainActivity.this,
"Location has changed",
Toast.LENGTH_LONG).show();
if(myLocation != null)
{
//latitude.setText("Current Latitude: " + String.valueOf(loc2.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(loc2.getLongitude()));
float[] results = new float[1];
Location.distanceBetween(lat3, lon3, myLocation.getLatitude(), myLocation.getLongitude(), results);
System.out.println("Distance is: " + results[0]);
dist += results[0];
DecimalFormat df = new DecimalFormat("#.##"); // adjust this as appropriate
if(count==1)
{
distance.setText(df.format(dist) + "meters");
}
lat3=myLocation.getLatitude();
lon3=myLocation.getLongitude();
count=1;
}
}
if(startButtonClicked == true)
{
startDistance=true;
}
//}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
counter= new MyCount(30000,1000);
counter.start();
n=n+1;
}
#Override
public void onTick(long millisUntilFinished) {
s1=millisUntilFinished;
r1=(30000-s1)/1000;
//e1.setText(String.valueOf(r1));
}
}}
Here is your problem: You are passing string values through intent when you expect the doubles in your second...
Intent intent = new Intent(MainActivity.this, FinishActivity.class);
intent.putExtra("dist","value");
intent.putExtra("time","durationValue");
startActivity(intent);
[EDIT] I assume you have 2 EditTexts to allow the user to enter the data. Lets say they are editText1 &editText2.
The EditTexts hold Strings so you need to convert/cast them.
Double value=Double.valueOf(editText1.getText().toString());
Double durationValue=Double.valueOf(editText2.getText().toString());
Also Make sure that you enter only digits in the EditTexts.
In your FirstActivity you are passing Strings instead of Doubles.
So instead of that you should use it like this:
intent.putExtra("dist",value);
intent.putExtra("time",durationValue);
Just omit the double Quotes " ".
notice that value and durationValue are must be Doubles in your code.
Hope it Helps.

How to get current location Latitude Longitude in android [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get Latitude and Longitude of the mobiledevice in android?
I need a straight forward code which only find the Latitude and Longitude.
I want to sent this over the webservice to get the near by hotels.
I have used a lot of codes they work very well but some time they didn't work.
If some one wants that code then I can also provide it is very good.
This is the code for getting user current latitude and longitude using geo coading in Android:
public class HomeActivity extends Activity implements LocationListener{
public static Context mContext;
private double latitude, longitude;
public LocationManager mLocManager;
// *******This is the new Code start on 11/4/2011 at 3 o'clock
/**
* This is the Home Button if user Login then it is move to TennisAppActivity otherwise move to Login
*
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homelayout);
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
this);
mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, this);
locationUpdate();
((Button) this.findViewById(R.id.ButtonHome))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
DefaultDisplay.class));
}
});
((Button) this.findViewById(R.id.ButtonProfile))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
MyProfile.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","MyProfile");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonNotifications))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
ShowAllNotificationActiviry.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","ShowAllNotificationActiviry");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonFavorites))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
FavoritesActivity.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","FavoritesActivity");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonMore))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
MoreListActivity.class));
}
});
}
public void locationUpdate()
{
CellLocation.requestLocationUpdate();
}
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
GUIStatics.currentAddress = obj.getSubAdminArea() + ","
+ obj.getAdminArea();
GUIStatics.latitude = obj.getLatitude();
GUIStatics.longitude = obj.getLongitude();
GUIStatics.currentCity= obj.getSubAdminArea();
GUIStatics.currentState= obj.getAdminArea();
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
// Toast.makeText(this, "Address=>" + add,
// Toast.LENGTH_SHORT).show();
// TennisAppActivity.showDialog(add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
GUIStatics.latitude=location.getLatitude();
GUIStatics.longitude= location.getLongitude();
Log.v("Test", "IGA" + "Lat" + latitude + " Lng" + longitude);
//mLocManager.r
getAddress(latitude, longitude);
if(location!=null)
{
mLocManager.removeUpdates(this);
}
// Toast.makeText(this, "Lat" + latitude + " Lng" + longitude,
// Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
if(arg1 ==
LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
}
else if(arg1== LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show();
}
}
}

gps not getting user location

I am trying to get the current user location (latitude and longitude ) but onLocationChanged method is not getting called
but other methods like public void onProviderDisabled(String provider). Please help, what can be the problem ?
I have a class:
package com.javacodegeeks.android.lbs;
import android.app.Activity;
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.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
public class HomeActivity extends Activity implements LocationListener{
public static Context mContext;
private double latitude, longitude;
public LocationManager mLocManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homelayout);
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
this);
mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, this);
locationUpdate();
((Button) this.findViewById(R.id.ButtonHome))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
DefaultDisplay.class));
}
});
((Button) this.findViewById(R.id.ButtonProfile))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
MyProfile.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","MyProfile");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonNotifications))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
ShowAllNotificationActiviry.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","ShowAllNotificationActiviry");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonFavorites))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
FavoritesActivity.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","FavoritesActivity");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonMore))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
MoreListActivity.class));
}
});
}
public void locationUpdate()
{
CellLocation.requestLocationUpdate();
}
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
GUIStatics.currentAddress = obj.getSubAdminArea() + ","
+ obj.getAdminArea();
GUIStatics.latitude = obj.getLatitude();
GUIStatics.longitude = obj.getLongitude();
GUIStatics.currentCity= obj.getSubAdminArea();
GUIStatics.currentState= obj.getAdminArea();
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
// Toast.makeText(this, "Address=>" + add,
// Toast.LENGTH_SHORT).show();
// TennisAppActivity.showDialog(add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
GUIStatics.latitude=location.getLatitude();
GUIStatics.longitude= location.getLongitude();
Log.v("Test", "IGA" + "Lat" + latitude + " Lng" + longitude);
//mLocManager.r
getAddress(latitude, longitude);
if(location!=null)
{
mLocManager.removeUpdates(this);
}
// Toast.makeText(this, "Lat" + latitude + " Lng" + longitude,
// Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
if(arg1 ==
LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
}
else if(arg1== LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show();
}
}
}
This is the my code i am using this for getting user current location.
Read it carefully the check what the mistake you have done in your code.
and also check all the permission in mainfest file related to gps.
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I hope this is help.
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
change this to 0 ....
Just extends the GpsStatus.Listener in your activity.
like as following:
ublic class MyActivity implements LocationListener,
GpsStatus.Listener
and check your permission:

android gps app for traffic application

I've currently finished learning the basics of android development and am trying to learn to make an android gps app in smartphones for my traffic system project. Not so very good yet in doing complicated codes. Please advise some resources or tutorials which will greatly help me to make this app.
- the app will send gps locations( lat & longitude and time ) via sms every 10 seconds once it approach a specific road section ( can be like 0.5 km length of road)
- if the phone passed that specific road section it will stop sending its locations
Why are you using the sms service to send the location? try using the webservice.
To implement this app you has to use the LocationManager and LocationListener libraries.
You can start by creating a gps listening class implementing the LocationListener, like the one shown below
public class CTLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
Log.w("LOCATION CHANGED", ""+location);
if(location != null) {
Constants.LATTITUDE = location.getLatitude();
Constants.LONGITUDE = location.getLongitude();
Constants.kAccuracy = location.getAccuracy();
Constants.ALTITUDE_VALUE = location.getAltitude();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("PROVIDER", "DISABLED:"+provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i("PROVIDER", "ENABLED:"+provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("EXTRAS", ""+extras);
Log.i("Provider status", ""+status);
}
}
Here I'm storing the updated locations on the Constants file. Start a sheduler that checks the locations periodically and start sending messages if they match your required locations.
To trigger the gps you can use
LocationListener locationListener = new CTLocationListener();
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1.0f, locationListener);
The scheduler you need is a timertask. This can be implemented as
public class showAccuracy extends TimerTask {
#Override
public void run() {
ghandler.post(new Runnable() {
#Override
public void run() {
if((Constants.Latitude == yourlatitude) && .....) {
}
}
});
}
}
public class HomeActivity extends Activity implements LocationListener{
public static Context mContext;
private double latitude, longitude;
public LocationManager mLocManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homelayout);
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
this);
mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, this);
locationUpdate();
((Button) this.findViewById(R.id.ButtonHome))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
DefaultDisplay.class));
}
});
((Button) this.findViewById(R.id.ButtonProfile))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
MyProfile.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","MyProfile");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonNotifications))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
ShowAllNotificationActiviry.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","ShowAllNotificationActiviry");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonFavorites))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
FavoritesActivity.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","FavoritesActivity");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonMore))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
MoreListActivity.class));
}
});
}
public void locationUpdate()
{
CellLocation.requestLocationUpdate();
}
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
GUIStatics.currentAddress = obj.getSubAdminArea() + ","
+ obj.getAdminArea();
GUIStatics.latitude = obj.getLatitude();
GUIStatics.longitude = obj.getLongitude();
GUIStatics.currentCity= obj.getSubAdminArea();
GUIStatics.currentState= obj.getAdminArea();
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
// Toast.makeText(this, "Address=>" + add,
// Toast.LENGTH_SHORT).show();
// TennisAppActivity.showDialog(add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
GUIStatics.latitude=location.getLatitude();
GUIStatics.longitude= location.getLongitude();
Log.v("Test", "IGA" + "Lat" + latitude + " Lng" + longitude);
//mLocManager.r
getAddress(latitude, longitude);
if(location!=null)
{
mLocManager.removeUpdates(this);
}
// Toast.makeText(this, "Lat" + latitude + " Lng" + longitude,
// Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
if(arg1 ==
LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
}
else if(arg1== LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show();
}
}
}
This is the code use for getting latitude and longitude or the device and also got the all information about the lat long using get address function .
here some other URL is very use full to you.
http://developer.android.com/reference/android/location/LocationManager.html
http://code.google.com/p/open-gpstracker/
http://androidcommunity.com/forums/f4/android-gps-support-and-info-55/
http://www.devx.com/wireless/Article/43005
http://android-er.blogspot.com/2011/02/get-locationlatitude-and-longitude-from.html
I hope this is very useful to you.

Gps location in android

I am using LocationManager to get the current location in android.for that ,i have used
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
GPS_PROVIDER as a service provide.while executing it returns null and shows the following in the log cat continuously.
V/libgps ( 116): DeferredActionThread pthread_cond_wait returned
Thanks in advance.
public class HomeActivity extends Activity implements LocationListener{
public static Context mContext;
private double latitude, longitude;
public LocationManager mLocManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homelayout);
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
this);
mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, this);
locationUpdate();
((Button) this.findViewById(R.id.ButtonHome))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
DefaultDisplay.class));
}
});
((Button) this.findViewById(R.id.ButtonProfile))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
MyProfile.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","MyProfile");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonNotifications))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
ShowAllNotificationActiviry.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","ShowAllNotificationActiviry");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonFavorites))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
FavoritesActivity.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","FavoritesActivity");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonMore))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
MoreListActivity.class));
}
});
}
public void locationUpdate()
{
CellLocation.requestLocationUpdate();
}
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
GUIStatics.currentAddress = obj.getSubAdminArea() + ","
+ obj.getAdminArea();
GUIStatics.latitude = obj.getLatitude();
GUIStatics.longitude = obj.getLongitude();
GUIStatics.currentCity= obj.getSubAdminArea();
GUIStatics.currentState= obj.getAdminArea();
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
// Toast.makeText(this, "Address=>" + add,
// Toast.LENGTH_SHORT).show();
// TennisAppActivity.showDialog(add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
GUIStatics.latitude=location.getLatitude();
GUIStatics.longitude= location.getLongitude();
Log.v("Test", "IGA" + "Lat" + latitude + " Lng" + longitude);
//mLocManager.r
getAddress(latitude, longitude);
if(location!=null)
{
mLocManager.removeUpdates(this);
}
// Toast.makeText(this, "Lat" + latitude + " Lng" + longitude,
// Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
if(arg1 ==
LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
}
else if(arg1== LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show();
}
}
}
I am using this code for getting latitude and longitude of current location of the user.
You should read it then convert it according to your requirement and also add the permission of using GPS in manifast file of your project.It is.
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I hope this is very helpful to you.
Test this Code and then Tel me if u have any Success!
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
and use following Permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
this ones Working fine on ma side.. you should try all this!

Categories

Resources