onLocationChanged() not called in Android - android

I'm developing a mini app to detect the current location of the user which i follow on this website http://androidexample.com/GPS_Basic__-__Android_Example/index.php?view=article_discription&aid=68 . I'm able to change the Lat and Lon in the extended control on the emulator itself. But when comes to using in my Xiaomi 1S (running version 4.2.2) phone it does not show any of my location. Below is my code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnSpoof = (Button) findViewById(R.id.btn_spoof);
lblShowLat = (TextView) findViewById(R.id.lblShowLat);
lblShowLon = (TextView) findViewById(R.id.lblShowLon);
lblShowTime = (TextView) findViewById(R.id.lblShowTime);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDateTime();
// Toast.makeText(getApplicationContext(), "Refresh ", Toast.LENGTH_LONG).show();
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
2);
}
}
lblShowLat.setText("No Lat");
lblShowLon.setText("No Lon");
}
#Override
//code does not run here
public void onLocationChanged(Location location) {
if(location !=null) {
lblShowLat.setText(Double.toString(location.getLatitude()));
lblShowLon.setText(Double.toString(location.getLongitude()));
String str = "Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude();
System.out.println("Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude());
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Unable to find your location, try again", Toast.LENGTH_SHORT).show();
}
}
Your help is appreciated thank you

I think You forgot to add this line ,
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,10,this);
and as well as ensure that device gps and network is enable or not with internet connectivity.

Please add these line ..it will work for you .
Add permission:-
android.permission.ACCESS_FINE_LOCATION
android.permission. ACCESS_COARSE_LOCATION
android.permission.INTERNET
In Java.class:-
#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");
}
}

Related

Isit possible to find the Current Location in Android using Latitude Longitude and Altitude

Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
OnCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_location_main);
//All textView
textViewNetLat = (TextView)findViewById(R.id.textViewNetLat);
textViewNetLng = (TextView)findViewById(R.id.textViewNetLng);
textViewGpsLat = (TextView)findViewById(R.id.textViewGpsLat);
textViewGpsLng = (TextView)findViewById(R.id.textViewGpsLng);
}
public void onDestroy() {
//Remove GPS location update
if(glocManager != null){
glocManager.removeUpdates(glocListener);
Log.d("ServiceForLatLng", "GPS Update Released");
}
//Remove Network location update
if(nlocManager != null){
nlocManager.removeUpdates(nlocListener);
Log.d("ServiceForLatLng", "Network Update Released");
}
super.onDestroy();
}
//This is for Lat lng which is determine by your wireless or mobile network
public class MyLocationListenerNetWork implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
nlat = loc.getLatitude();
nlng = loc.getLongitude();
//Setting the Network Lat, Lng into the textView
textViewNetLat.setText("Network Latitude: " + nlat);
textViewNetLng.setText("Network Longitude: " + nlng);
Log.d("LAT & LNG Network:", nlat + " " + nlng);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d("LOG", "Network is OFF!");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d("LOG", "Thanks for enabling Network !");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
//This is for Lat lng which is determine by your device GPS
public class MyLocationListenerGPS implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
glat = loc.getLatitude();
glng = loc.getLongitude();
//Setting the GPS Lat, Lng into the textView
textViewGpsLat.setText("GPS Latitude: " + glat);
textViewGpsLng.setText("GPS Longitude: " + glng);
Log.d("LAT & LNG GPS:", glat + " " + glng);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d("LOG", "GPS is OFF!");
}
#Override
public void onProviderEnabled(String provider)
{
Log.d("LOG", "Thanks for enabling GPS !");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public void showLoc(View v) {
//Location access ON or OFF checking
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
boolean networkWifiStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.NETWORK_PROVIDER);
//If GPS and Network location is not accessible show an alert and ask user to enable both
if(!gpsStatus || !networkWifiStatus)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(GetLocationMainActivity.this);
alertDialog.setTitle("Make your location accessible ...");
alertDialog.setMessage("Your Location is not accessible to us.To show location you have to enable it.");
alertDialog.setIcon(R.drawable.warning);
alertDialog.setNegativeButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
});
alertDialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Toast.makeText(getApplicationContext(), "Remember to show location you have to enable it !", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
alertDialog.show();
}
//IF GPS and Network location is accessible
else
{
nlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
nlocListener = new MyLocationListenerNetWork();
nlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 1, 0, nlocListener);
glocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
glocListener = new MyLocationListenerGPS();
glocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 1, 0, glocListener);
}
}
}
This Looks similar:
Google api
It is javasript, but you can use the Google api in andriod as well :-)

Asynctask implements LocationListener : onLocationChanged never called

I make a simple code who allow an user to get his current GPS position when he push some button.
So, i create a MainActivity and an Asynctask class, the Asynctask implements LocationListener but the override onLocationChanged is never call ! (no trace in LogCat..)
Then, I get gps data but he never change when I push the button :/
And if I leave the application, if I force the processus to exit in parameter option Android and I launch again my apps, the gps data keep same. I don't understand that..and why the override method is never called.
Here my only file :
public class MainActivity extends Activity {
public static Context context;
public Button push = null;
public getGPS tache_getGPS = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplication().getApplicationContext();
push = (Button) findViewById(R.id.button);
push.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("T: onClick", "debut");
tache_getGPS = new getGPS();
tache_getGPS.execute();
Log.i("T: onClick", "fin");
// TODO Auto-generated method stub
}
});
}
#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;
}
}
class getGPS extends AsyncTask<Void, Integer, Location> implements
LocationListener {
final long REFRESH = 5 * 1000;
private Location location;
private LocationManager lm;
protected void onPreExecute() {
Log.i("T: onPreExcute", "debut");
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
// Configure location manager - I'm using just the network provider in
// this example
lm = (LocationManager) MainActivity.context
.getSystemService(Context.LOCATION_SERVICE);
String best = lm.getBestProvider(crit, false);
Log.i("T: onPreExecute", "best : " + best);
lm.requestLocationUpdates(best, 0, 1, this);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// nearProgress.setVisibility(View.VISIBLE);
Log.i("T: onPreExcute", "fin");
}
protected Location doInBackground(Void... params) {
Log.i("T: doInBackground", "debut");
// Try to use the last known position
Location lastLocation = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
/*
// If it's too old, get a new one by location manager
if (System.currentTimeMillis() - lastLocation.getTime() > REFRESH) {
while (location == null)
try {
Thread.sleep(100);
} catch (Exception ex) {
}
return location;
}
*/
Log.i("T: doInBackground", "fin");
return lastLocation;
}
protected void onPostExecute(Location location) {
Log.i("T: onPostExecute", "debut");
// nearProgress.setVisibility(View.GONE);
lm = (LocationManager) MainActivity.context
.getSystemService(Context.LOCATION_SERVICE);
lm.removeUpdates(this);
Log.i("T: onPostExecute",
"Altitude : " + String.valueOf(location.getAltitude()));
Log.i("T: onPostExecute",
"Longitude : " + String.valueOf(location.getLongitude()));
Log.i("T: onPostExecute",
"Latitude : " + String.valueOf(location.getLatitude()));
Log.i("T: onPostExecute",
"Precision(mètre) : " + String.valueOf(location.getAccuracy()));
Log.i("T: onPostExecute", "fin");
Toast.makeText(
MainActivity.context,
"Altitude : " + String.valueOf(location.getAltitude()) + "\n"
+ "Longitude : "
+ String.valueOf(location.getLongitude()) + "\n"
+ "Latitude : "
+ String.valueOf(location.getLatitude()) + "\n"
+ "Precision(mètre) : "
+ String.valueOf(location.getAccuracy()),
Toast.LENGTH_SHORT).show();
return;
}
#Override
public void onLocationChanged(Location newLocation) {
Log.i("T: onLocationChanged", "debut");
location = newLocation;
Log.i("T: onLocationChanged", "fin");
}
#Override
public void onProviderDisabled(String provider) {
Log.i("T: onProviderDisabled", provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i("T: onProviderEnabled", provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("T: onStatusChanged", "provider : " + provider);
Log.i("T: onStatusChanged", "status : " + status);
Log.i("T: onStatusChanged", "extras : " + extras.toString());
}
}
Thanks for help, and sorry for my poor english writing x)
NEW CODE (after advises =) ), without Asinctask
public class MainActivity extends Activity implements LocationListener{
public static Context context;
public Button push = null;
public getGPS tache_getGPS = null;
private Location location;
private LocationManager lm;
final long REFRESH = 5 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplication().getApplicationContext();
push = (Button) findViewById(R.id.button);
push.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("T: onClick", "debut");
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location lastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (System.currentTimeMillis() - lastLocation.getTime() > REFRESH) {
while (location == null)
try { Thread.sleep(100); } catch (Exception ex) { }
Log.i("FINAL : location", location.toString());
Toast.makeText(MainActivity.context, "location : "+location.toString(), Toast.LENGTH_SHORT).show();
return;
}
Log.i("FINAL : lastlocation", lastLocation.toString());
Toast.makeText(MainActivity.context, "lastLocation : "+lastLocation.toString(), Toast.LENGTH_SHORT).show();
Log.i("T: onClick", "fin");
}
});
}
#Override
protected void onResume(){
super.onResume();
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
lm = (LocationManager) MainActivity.context.getSystemService(Context.LOCATION_SERVICE);
String best = lm.getBestProvider(crit, false);
Log.i("T: onPreExecute", "best : " + best);
lm.requestLocationUpdates(best, 1, 1, this);
}
#Override
protected void onPause(){
super.onPause();
lm.removeUpdates(this);
}
#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;
}
#Override
public void onLocationChanged(Location newLocation) {
Toast.makeText(context, "onLocationChanged", Toast.LENGTH_SHORT).show();
Log.i("T: onLocationChanged", "debut");
location = newLocation;
Log.i("T: onLocationChanged", "fin");
}
#Override
public void onProviderDisabled(String provider) {
Log.i("T: onProviderDisabled", provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i("T: onProviderEnabled", provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("T: onStatusChanged", "provider : " + provider);
Log.i("T: onStatusChanged", "status : " + status);
Log.i("T: onStatusChanged", "extras : " + extras.toString());
}
}
In requestLocationUpdates you specified 1 as the minDistance (minDistance is the minimum distance interval for notifications, in meters). Try to set it to 0.

Location listener in android gives java.lang.IllegalArgumentException: listener==null

Hey While I am running the application it gives a error java.lang.IllegalArgumentException: listener==null , that tells that listener is null.
My sample code is here:
public class HelloAndroidGpsActivity extends Activity {
private EditText editTextShowLocation;
private Button buttonGetLocation;
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buttonGetLocationClick();
}
});
}
/** Gets the current location and update the mobileLocation variable*/
private void getCurrentLocation() {
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
System.out.println("mobile location manager is ="+locManager);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
locListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
System.out.println("mobile location is in listener1");
}
#Override
public void onProviderEnabled(String provider) {
System.out.println("mobile location is in listener2");
}
#Override
public void onProviderDisabled(String provider) {
System.out.println("mobile location is in listener3");
}
#Override
public void onLocationChanged(Location location) {
System.out.println("mobile location is in listener="+location);
mobileLocation = location;
}
};
System.out.println("after setting listener");
}
private void buttonGetLocationClick() {
getCurrentLocation();
System.out.println("mobile location is ="+mobileLocation);
if (mobileLocation != null) {
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + mobileLocation.getLongitude();
String latitude = "Latitude: " + mobileLocation.getLatitude();
String altitiude = "Altitiude: " + mobileLocation.getAltitude();
String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
String time = "Time: " + mobileLocation.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n"
+ altitiude + "\n" + accuracy + "\n" + time);
} else {
editTextShowLocation.setText("Sorry, location is not determined");
}
}
}
Output in textbox is "Sorry, location is not determined""
If any one can tell me what is the problem then please help me.
Thank you
Initialize the listener before you use it.
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
At this point of time, locListener is null, and you are initializing it after this line of code. This may be the reason.
So rearrange the lines of your code like this;
locListener = new LocationListener() {...};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
Hope this may help to solve your issue...

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.

Unable to toast latitude and longitude

Am working on an app, which toasts the latitude and longitude using LocationManager and LocationListener. On running the app, an error shows up saying "Sorry, Process system is not responding.". This happens when I supply the lat and long either manually from emulator control under DDMS or from command prompt using telnet.
Java Code:
public class LocationFinder extends Activity {
private LocationManager locManager;
private LocationListener locListener;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locListener = new MyLocationListener();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(loc != null){
Toast.makeText(getBaseContext(), "Latitude: " + loc.getLatitude() + "Longitude: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
}
}
#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
}
}
}
And I have set the following permissions in manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
The emulator is also hw.gps enabled.
I would like to know if there is anything wrong with my code.
Thanks
Check by using Log that you are getting Values for Latitude and longitude..
Then in Toast put this
Toast.makeText(LocationFinder.this, "Latitude: " + loc.getLatitude() + "Longitude: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
instead of
Toast.makeText(getBaseContext(), "Latitude: " + loc.getLatitude() + "Longitude: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
// Des: Start Device's GPS and get current latitude and longitude
public void GPS() throws IOException {
// Des: This is a background service and called after every 10 minutes and fetch latitude-longitude values
background = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < j; i++) {
if (ProjectStaticVariable.GPSExit == true ) {
try {
Thread.sleep(600000); //10 minutes
mainhandler.sendMessage(mainhandler.obtainMessage());
j++;
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
});
background.start();
mainhandler = new Handler() {
public void handleMessage(Message msg) {
// Check Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
lat_long_Service_flag = true;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener(getApplicationContext());
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, mlocListener);
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
}
};
}
// Des: Location Listener through which we get current latitude and longitude
public class MyLocationListener implements LocationListener {
public MyLocationListener(Context mContext) {}
public MyLocationListener(Runnable runnable) {}
#Override
public void onLocationChanged(Location loc) {
longitude = loc.getLongitude();
latitude = loc.getLatitude();
final_latitude = Double.toString(latitude);
final_longitude = Double.toString(longitude);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

Categories

Resources