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.
Related
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");
}
}
I need my Actual position in GPS just once.
In this code, onLocationChanged is never called, I don't understand why.
As I call it:
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
It should run every 0 sec and every 0 meters.
How can I change the code so that it works?
public class MapActivity extends FragmentActivity implements
LocationListener {
private final String TAG = getClass().getSimpleName();
private GoogleMap mMap;
private Location loc;
private Context ctx;
private radius;
LocationManager mLocationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
ctx = MapActivity.this;
radius = getRadius();
mMap = initMap();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
loc = location;
Log.v("Location Changed", location.getLatitude() + " and "
+ location.getLongitude());
mLocationManager.removeUpdates(this);
myPlaces = new GetPlaces(ctx, GAS_STATION, mMap, loc, radius);
myPlaces.execute();
Log.e(TAG, "location : " + loc);
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
EDIT : I moved the call to loc :
myPlaces = new GetPlaces(ctx, GAS_STATION, mMap, loc, radius);
myPlaces.execute();
Log.e(TAG, "location : " + loc);
inside the onLocationChange. This way, I don't get nullpointerException anymore, but I can wait more than 20 sec to get location. It is not so good... If anybody have an idea of how to get the fix quickly!
What I did is add 2 listener, not only gps, but also network before onCreate :
Found the code here : Location Manager's requestLocationUpdates called only once
private final LocationListener gpsLocationListener =new LocationListener(){
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
final String tvTxt = textView.getText().toString();
switch (status) {
case LocationProvider.AVAILABLE:
textView.setText(tvTxt + "GPS available again\n");
break;
case LocationProvider.OUT_OF_SERVICE:
textView.setText(tvTxt + "GPS out of service\n");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
textView.setText(tvTxt + "GPS temporarily unavailable\n");
break;
}
}
#Override
public void onProviderEnabled(String provider) {
textView.setText(textView.getText().toString()
+ "GPS Provider Enabled\n");
}
#Override
public void onProviderDisabled(String provider) {
textView.setText(textView.getText().toString()
+ "GPS Provider Disabled\n");
}
#Override
public void onLocationChanged(Location location) {
locationManager.removeUpdates(networkLocationListener);
textView.setText(textView.getText().toString()
+ "New GPS location: "
+ String.format("%9.6f", location.getLatitude()) + ", "
+ String.format("%9.6f", location.getLongitude()) + "\n");
}
};
private final LocationListener networkLocationListener =
new LocationListener(){
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
final String tvTxt = textView.getText().toString();
switch (status) {
case LocationProvider.AVAILABLE:
textView.setText(tvTxt + "Network location available again\n");
break;
case LocationProvider.OUT_OF_SERVICE:
textView.setText(tvTxt + "Network location out of service\n");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
textView.setText(tvTxt
+ "Network location temporarily unavailable\n");
break;
}
}
#Override
public void onProviderEnabled(String provider) {
textView.setText(textView.getText().toString()
+ "Network Provider Enabled\n");
}
#Override
public void onProviderDisabled(String provider) {
textView.setText(textView.getText().toString()
+ "Network Provider Disabled\n");
}
#Override
public void onLocationChanged(Location location) {
textView.setText(textView.getText().toString()
+ "New network location: "
+ String.format("%9.6f", location.getLatitude()) + ", "
+ String.format("%9.6f", location.getLongitude()) + "\n");
}
};
and activate them in CallBack methods :
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
networkLocationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, gpsLocationListener);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(networkLocationListener);
locationManager.removeUpdates(gpsLocationListener);
}
And then it worked well! I think just GPS is not enough, because fix can last a lot to come !
I need to calculate the current latiude and longitude of the user before he logs in. I have tested my code in my mobile device but it does not seem to work. Here is my code :
LocationManager mlocManager=null;
LocationListener mlocListener=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
}
#Override protected void onResume() {
super.onResume();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, mlocListener);
}
#Override protected void onPause() {
super.onPause();
mlocManager.removeUpdates(mlocListener); //<8>
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
Toast.makeText(getApplicationContext(),"In onchange", Toast.LENGTH_SHORT).show();
if(loc!=null){
latitude=loc.getLatitude();
longitude=loc.getLongitude();
if(loc.getLatitude()!=0.0 || loc.getLongitude()!=0.0){
Toast.makeText(getApplicationContext(),"Location not null", Toast.LENGTH_SHORT).show();
SharedPreferences prefsSaveLatLong = context.getSharedPreferences("prefsSaveLatLong",Context.MODE_PRIVATE);
SharedPreferences.Editor e = prefsSaveLatLong.edit();
e.remove("LAT");
e.remove("LONG");
e.putString("LAT",Double.toString(loc.getLatitude()));
e.putString("LONG",Double.toString(loc.getLongitude()));
e.commit();
String Text = "My current location is: " + "Latitude = " + loc.getLatitude() + "Longitude = " + loc.getLongitude();
Toast.makeText(getApplicationContext(),Text+" "+latitude+" "+longitude, Toast.LENGTH_SHORT).show();
}else{
SharedPreferences prefsSaveLatLong = context.getSharedPreferences("prefsSaveLatLong",Context.MODE_PRIVATE);
if(prefsSaveLatLong.contains("LAT") && prefsSaveLatLong.contains("LONG")){
SharedPreferences.Editor e1 = prefsSaveLatLong.edit();
e1.remove("LAT");
e1.remove("LONG");
e1.commit();
}
}
// set latitude longitude to label
setLatLongLabel();
}else{
latLongLabel.setTextColor(Color.parseColor("#FF0000"));
latLongLabel.setText("Latitude-Longitude not available");
SharedPreferences prefsSaveLatLong = context.getSharedPreferences("prefsSaveLatLong",Context.MODE_PRIVATE);
if(prefsSaveLatLong.contains("LAT") && prefsSaveLatLong.contains("LONG")){
SharedPreferences.Editor e1 = prefsSaveLatLong.edit();
e1.remove("LAT");
e1.remove("LONG");
e1.commit();
}
}
}
#Override
public void onProviderDisabled(String provider)
{
gpsEnabled=false;
if(!gpsEnabled){
Toast.makeText( getApplicationContext(),"Gps Disabled", Toast.LENGTH_SHORT ).show();
showSettingsAlert();
}
}
#Override
public void onProviderEnabled(String provider)
{
gpsEnabled=true;
Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
if(status==0){
Toast.makeText(getApplicationContext(),"OUT_OF_SERVICE",Toast.LENGTH_SHORT).show();
SharedPreferences prefsSaveLatLong = context.getSharedPreferences("prefsSaveLatLong",Context.MODE_PRIVATE);
if(prefsSaveLatLong.contains("LAT") && prefsSaveLatLong.contains("LONG")){
SharedPreferences.Editor e1 = prefsSaveLatLong.edit();
e1.remove("LAT");
e1.remove("LONG");
e1.commit();
}
}
else if(status==1){
Toast.makeText(getApplicationContext(),"TEMPORARILY_UNAVAILABLE",Toast.LENGTH_SHORT).show();
}else if(status==2){
Toast.makeText(getApplicationContext(),"AVAILABLE",Toast.LENGTH_SHORT).show();
}
}
}/* End of Class MyLocationListener */enter code here
`
Try some thing like this
public class ShowLocationActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
See this tutorial
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...
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) {
}
}