編輯:Android 技術基礎
GPS 這個名詞大家都不陌生。Android 中的定位方式通常有四種:GPS 定位、WiFi 定位、基站定位以及 AGPS(基站 + GPS 輔助)。本系列只講 GPS 定位的基本用法。
GPS 通過與衛星交互獲取設備經緯度,精度較高,缺點也很明顯:幾乎無法在室內使用,通常需要接收到 4 顆及以上衛星信號才能保證定位精度。但如果在室外,即使沒有網絡,GPS 依然可用。
這是系統服務,不能直接 new:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
并且別忘了加權限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
常用方法:
它是 GPS 定位組件的抽象表示,可以通過它查詢定位方式的特性:
用于告訴系統你需要什么樣的定位方式:
運行效果:

可以看到當前可用的 Provider 有三個:
布局 activity_main.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button android:id="@+id/btn_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="獲得系統所有的 LocationProvider" />
<Button android:id="@+id/btn_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="根據條件獲取 LocationProvider" />
<Button android:id="@+id/btn_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="獲取指定的 LocationProvider" />
<TextView android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:background="#81BB4D"
android:padding="5dp"
android:textColor="#FFFFFF"
android:textSize="20sp" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_one, btn_two, btn_three;
private TextView tv_result;
private LocationManager lm;
private List<String> pNames = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
bindViews();
}
private void bindViews() {
btn_one = (Button) findViewById(R.id.btn_one);
btn_two = (Button) findViewById(R.id.btn_two);
btn_three = (Button) findViewById(R.id.btn_three);
tv_result = (TextView) findViewById(R.id.tv_result);
btn_one.setOnClickListener(this);
btn_two.setOnClickListener(this);
btn_three.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_one:
pNames.clear();
pNames = lm.getAllProviders();
tv_result.setText(getProvider());
break;
case R.id.btn_two:
pNames.clear();
Criteria criteria = new Criteria();
criteria.setCostAllowed(false); // 免費
criteria.setAltitudeRequired(true); // 能提供高度
criteria.setBearingRequired(true); // 能提供方向
pNames = lm.getProviders(criteria, true);
tv_result.setText(getProvider());
break;
case R.id.btn_three:
pNames.clear();
pNames.add(lm.getProvider(LocationManager.GPS_PROVIDER).getName());
tv_result.setText(getProvider());
break;
}
}
/** 遍歷集合并拼接為字符串 */
private String getProvider() {
StringBuilder sb = new StringBuilder();
for (String s : pNames) {
sb.append(s).append("\n");
}
return sb.toString();
}
}
使用 GPS 前的第一件事,是判斷它是否可用;不可用時要引導用戶去打開。
private boolean isGpsAble(LocationManager lm) {
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
方法一:強制打開(Android 5.0 之后已失效)
// 5.0 以前可用
private void openGPS(Context context) {
Intent gpsIntent = new Intent();
gpsIntent.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
gpsIntent.addCategory(Intent.CATEGORY_ALTERNATIVE);
gpsIntent.setData(Uri.parse("custom:3"));
try {
PendingIntent.getBroadcast(context, 0, gpsIntent, 0).send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
}
方法二:跳轉位置設置頁,由用戶自行開啟(推薦)
private void openGPS2() {
startActivityForResult(
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
新版系統出于用戶隱私保護,已經不允許應用靜默開啟定位服務,方法二是唯一得體的做法。
調用 requestLocationUpdates 并實現 LocationListener 即可。
布局 activity_location.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:id="@+id/tv_show"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:textSize="20sp" />
</LinearLayout>
LocationActivity.java:
public class LocationActivity extends AppCompatActivity {
private LocationManager lm;
private TextView tv_show;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
tv_show = (TextView) findViewById(R.id.tv_show);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!isGpsAble(lm)) {
Toast.makeText(this, "請打開 GPS~", Toast.LENGTH_SHORT).show();
openGPS2();
}
// 先取一次最近的已知位置,避免等待首個定位
Location lc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateShow(lc);
// 間隔 2 秒、位移 8 米更新一次
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 8, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
updateShow(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) {
updateShow(lm.getLastKnownLocation(provider));
}
@Override
public void onProviderDisabled(String provider) {
updateShow(null);
}
});
}
private void updateShow(Location location) {
if (location == null) {
tv_show.setText("");
return;
}
StringBuilder sb = new StringBuilder();
sb.append("當前的位置信息:\n");
sb.append("經度:" + location.getLongitude() + "\n");
sb.append("緯度:" + location.getLatitude() + "\n");
sb.append("高度:" + location.getAltitude() + "\n");
sb.append("速度:" + location.getSpeed() + "\n");
sb.append("方向:" + location.getBearing() + "\n");
sb.append("定位精度:" + location.getAccuracy() + "\n");
tv_show.setText(sb.toString());
}
private boolean isGpsAble(LocationManager lm) {
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
private void openGPS2() {
startActivityForResult(
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 記得取消監聽,否則會內存泄漏并持續耗電
if (lm != null) lm.removeUpdates(locationListener);
}
}
因為 GPS 必須在室外才能用,于是趁機出門買了杯奶茶,順道截下圖:

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
當時間間隔超過 minTime(毫秒)或位移超過 minDistance(米)時,就會回調 listener。官方建議 minTime 不低於 60000(1 分鐘),更省電;如果需要盡可能實時,可以都設為 0,但要注意電量消耗。
權限也要記得聲明(Android 6.0 以上需動態申請):
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
固定一個坐標,當設備與它的距離小于指定半徑時觸發對應處理——這就是地理圍欄。通過 addProximityAlert 添加:
addProximityAlert(double latitude, double longitude, float radius, long expiration, PendingIntent intent)
ProximityActivity.java:
public class ProximityActivity extends AppCompatActivity {
private LocationManager lm;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proximity);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
double longitude = 113.56843;
double latitude = 22.374937;
float radius = 10; // 半徑,單位米
Intent intent = new Intent(this, ProximityReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, -1, intent, 0);
lm.addProximityAlert(latitude, longitude, radius, -1, pi);
}
}
再寫一個廣播接收者用于接收觸發事件。ProximityReceiver.java:
public class ProximityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean isEnter = intent.getBooleanExtra(
LocationManager.KEY_PROXIMITY_ENTERING, false);
if (isEnter) {
Toast.makeText(context, "你已到達南軟 B1 棟附近", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "你已離開南軟 B1 棟附近", Toast.LENGTH_LONG).show();
}
}
}
别忘了在清單里注冊:
<receiver android:name=".ProximityReceiver"/>
運行效果:設定了 10m 的範圍,結果從 B1 走到 D1 那邊明顯不止 10m,前后還正好下雨。

本節介紹了 Android 中 GPS 定位的基本用法:核心 API、獲取 Provider、判斷與引導開啟定位、實時位置更新以及地理圍欄。內容部分參考李剛老師的《Android 瘋狂講義》,示例做了一些修改并補充了可用性說明。
最后補充一點:實際項目中更推薦使用 Google Play Services 的 FusedLocationProviderClient,它會自動在 GPS、WiFi、基站之間切換并智能取最優結果,比直接操作 LocationManager 更省電也更省心。
底部導航加 ViewPager:打造可滑動切換的 Fragment 頁面
從底部導航到可滑動頁面前三篇使用不同方式完成底部導航後,可以進一步加入 ViewPager,讓使用者除了點擊底部選單,也能以左右滑動切換頁面。這種做法在內容型 App 中
JSON 解析實戰:在 Android 中把資料寫成檔案再讀回來
JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,可讀性佳、撰寫方便,能在不同平台之間傳遞資料,是目前行動端與伺服器溝通最常見的
進階底部導航:為 Fragment 選單加上紅點與訊息數量
從普通選單到帶提醒的底部導航一般底部導航只需要切換頁面,但許多即時通訊或社群 App 還會在選單上顯示紅點、數字或提醒標記。若使用簡單的 TextView 或 Radio
搞定 ListView 裡 CheckBox 的經典錯位問題
本節引言: 只要你在自定義的 ListView item 裡放了一個 CheckBox,當列表項超過一屏,幾乎一定會撞上這個經典坑——滾動時勾選狀態亂竄。下面我們先剖析它