1.布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.test.os.gpstest.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/location_tv" /> </LinearLayout>
2.声明权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
3.android 6以上需要动态请求权限
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1); }
4.获取LocationManager实例
locationManage = (LocationManager) getSystemService(LOCATION_SERVICE);
5.设置定位准则
Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE);//粗略精度 criteria.setAltitudeRequired(false);//是否需要返回海拔信息 criteria.setBearingRequired(false);//是否需要返回方向信息 criteria.setCostAllowed(true); //是否允许付费服务 criteria.setPowerRequirement(Criteria.ACCURACY_HIGH); //电量消耗等级 criteria.setSpeedRequired(false); //是否需要返回速度信息
6.获取Location 实例
String currentProvider = locationManage.getBestProvider(criteria,true); location = locationManage.getLastKnownLocation(currentProvider);//获取最后一次位置信息
7.设置LocationListener监听
LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { getLocationInfo(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; locationManage.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000, 0,locationListener);
8.获取定位信息
private void getLocationInfo(Location location) { if(location != null){ double lag = location.getLatitude(); double lng = location.getLongitude(); double speed = location.getSpeed(); float acc = 0; if(location.hasAccuracy()){ acc = location.getAccuracy(); } double height = 0; if(location.hasAltitude()) { height = location.getAltitude(); } float bear = 0; if(location.hasBearing()){ bear = location.getBearing(); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("经纬度是: ") .append(lag) .append("\n") .append("纬度是: ") .append(lng) .append("\n速度是: ") .append(speed) .append("\n精度是: ") .append(acc) .append("\n高度是: ") .append(height) .append("\n风向是: ") .append(bear); tv_location.setText(stringBuilder.toString()); }else { tv_location.setText("没有获取到信息"); } }