package com.example.locationtest;
import java.util.List;
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.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView positionTextView;//用来显示当前位置信息
private LocationManager locationmanager;//位置管理器
private String provider;//用GPS还是网络来定位
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;
//如果是用GPS来定位
}
else if(providerList.contains(LocationManager.NETWORK_PROVIDER)){
provider = LocationManager.NETWORK_PROVIDER;
//如果是用网络来定位
}
else{
Toast.makeText(this, "No location provider to use", Toast.LENGTH_SHORT).show();
//无可用定位工具
return;
}
Location location = locationmanager.getLastKnownLocation(provider);
//得到最近位置
if(location!=null){
showLocation(location);//位置存在则显示位置
}
locationmanager.requestLocationUpdates(provider, 5000, 10, locationListener);//位置更新器,侦听每5S/10M的位置改变
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(locationmanager!=null){
locationmanager.removeUpdates(locationListener);
}
}
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);
}
};
private void showLocation(Location location){
String currentPosition = "latitude is"+location.getLatitude()+"\n"//经度
+"longitude is"+location.getLongitude()+"\n"+//纬度
"altitude is" + location.getAltitude()//海拔
;
positionTextView.setText(currentPosition);
}
}
Android调用系统功能获取当前经纬度
最新推荐文章于 2024-04-08 12:32:31 发布