I want to latitude and longtitude at current location. it run work on emulator but give lat/long 0.0 on mobile device. my device is LG 4x hd. src/.java file :
private TextView txt_lat,txt_lon,txt_gps;
private LocationManager lm;
double lat, lon;
protected LocationListener locatlist;
Location locat;
GpsStatus.Listener gpslist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt_lat= (TextView) findViewById(R.id.textView2);
txt_lon= (TextView) findViewById(R.id.textView4);
txt_gps = (TextView) findViewById(R.id.textView5);
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locat = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(locat != null) {
lat = locat.getLatitude();
lon = locat.getLongitude();
}
locatlist = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat = location.getLatitude();
lon = location.getLongitude();
txt_lat.setText("lat : "+lat);
txt_lon.setText("lon : "+lon);
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locatlist);
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
txt_gps.setText("GPS is started");
}
else if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
txt_gps.setText("GPS is non-start");
}
txt_lat.setText("lat : "+lat);
txt_lon.setText("lon : "+lon);
}
@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;
}
mainfest permission :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
lat long is forever 0.0 on device but it work on emulator. its a simple code and why its not working ? Where i am going wrong ?
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);-->may be here you get null value of location manager replace with this line
lm = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.