package com.example.zuobiao; import java.util.List; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); LocationManager manager = (LocationManager) getSystemService(LOCATION_SERVICE); List<String> allProviders = manager.getAllProviders(); //第二个表示多少秒刷新,第三个表示多少米刷新都写成0表示实时刷新 manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() { //provider状态改变时候回调 @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { // TODO Auto-generated method stub } //用户打开 @Override public void onProviderEnabled(String arg0) { // TODO Auto-generated method stub } //用户关闭gps @Override public void onProviderDisabled(String arg0) { // TODO Auto-generated method stub } //变化时候调用 @Override public void onLocationChanged(Location lo) { // TODO Auto-generated method stub String j = "经度"+lo.getLongitude(); String w = "维度"+lo.getLatitude(); String accuracy = "误差"+lo.getAccuracy(); String altitude = "海拔"+lo.getAltitude(); tv.setText(j+" "+w+" "+accuracy+" "+altitude); } }); } }
拿到最佳的位置提供者
manager = (LocationManager) getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setCostAllowed(true);// 是否允许付费,比如使用3g网络定位 criteria.setAccuracy(Criteria.ACCURACY_FINE); String bestProvider = manager.getBestProvider(criteria, true);// 获取最佳位置提供者 listener = new Mlistener(); manager.requestLocationUpdates(bestProvider, 0, 0, listener);// 参1表示位置提供者,参2表示最短更新时间,参3表 //示最短更新距离
清单文件需要配置权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>