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.设置定位准则
6.获取Location 实例
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.获取定位信息
文章来源: GPS定位