点击按钮根据GPS获取当前经纬度

1:Android2.3以后就禁止代码打开GPS了,需要用以下代码跳转到设置面板

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS );

context.startActivity(intent);

2:

主活动:MainActivity

  private double latitude = 0.0;
private double longitude = 0.0;


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);

      btn_show=(Button)findViewById(R.id.btn_getloc);
btn_show.setOnClickListener(this);
edt_lat=(EditText)findViewById(R.id.edt_lat);
edt_lon=(EditText)findViewById(R.id.edt_lon);
}


public void onClick(View v) {
if(v.getId()==R.id.btn_getloc)
{
getlocation();
String lat_str=String.valueOf(latitude);
String lon_str=String.valueOf(longitude);
edt_lat.setText(lat_str);
edt_lon.setText(lon_str);
}
}


void getlocation() 
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) 
{
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
} else 
{
LocationListener locationListener = new LocationListener() 
{
// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
// Provider被enable时触发此函数,比如GPS被打开
@Override
public void onProviderEnabled(String provider) {
}
// Provider被disable时触发此函数,比如GPS被关闭
@Override
public void onProviderDisabled(String provider) {
}
// 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
@Override
public void onLocationChanged(Location location) {
if (location != null) {
latitude = location.getLatitude(); // 纬度
longitude = location.getLongitude(); // 经度
}
}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 0,
locationListener);
Location location1 = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location1 != null) {
latitude = location1.getLatitude(); // 经度
longitude = location1.getLongitude(); // 纬度
}
}
}else
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS );
startActivity(intent);
}
}


3:AndroidManifest.xml  文件见权限


  <!-- 连接互联网Internet权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- GPS定位权限 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"/>
   


展开阅读全文

没有更多推荐了,返回首页