使用getLastKnownLocation()来获取location值为空的问题
绵羊mie 2016-04-17 12:05:28 public class MainActivity extends Activity {
private TextView positionTextView;
private LocationManager locationManager;
private String provider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
positionTextView =(TextView)findViewById(R.id.position_text_view);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//获取所有可用的位置提供器
List<String> providerList=locationManager.getProviders(true);
if(providerList.contains(LocationManager.GPS_PROVIDER))
{
provider=LocationManager.GPS_PROVIDER;
}
else if(providerList.contains(LocationManager.NETWORK_PROVIDER))
{
provider=LocationManager.NETWORK_PROVIDER;
}
else {
Toast.makeText(this,"No location provider to use",Toast.LENGTH_LONG).show();
return;
}
Location location=locationManager.getLastKnownLocation(provider);
if(location!=null)
{
//显示当前位置信息
showLocation(location);
}
else {
Toast.makeText(MainActivity.this,"Location为空",Toast.LENGTH_LONG).show();
}
locationManager.requestLocationUpdates(provider, 5000,1,locationListener);
}
@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;
}
private void showLocation(Location location)
{
String currentPositionString="latitude is"+location.getLatitude()+"\n"+"longitude id"
+location.getLatitude();
positionTextView.setText(currentPositionString);
}
LocationListener locationListener =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
showLocation(location);
}
};
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(locationManager!=null)
{
//移除监听
locationManager.removeUpdates(locationListener);
}
}
}
使用gps定位将定位后的信息显示在textview上 但是定位方法为gps的时候location的值为空使用网络定位时就好用