編輯:關於 Android 程式設計
它是系統服務,不能直接 new:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
並且別忘了申請定位權限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
拿到實例後,常用的方法有這些:
addGpsStatusListener(GpsStatus.Listener):註冊 GPS 狀態監聽。addProximityAlert(lat, lng, radius, expiration, intent):添加臨近警告。getAllProviders():返回所有 LocationProvider。getBestProvider(Criteria, boolean):按條件取最優 Provider。getGpsStatus(GpsStatus):獲取 GPS 狀態。getLastKnownLocation(String provider):取指定 Provider 最近一次已知位置。getProvider(String name) / getProviders(...):按名稱或條件取 Provider。isProviderEnabled(String provider):判斷某 Provider 是否可用。removeGpsStatusListener(...) / removeProximityAlert(...):移除監聽與警告。requestLocationUpdates(...):週期性獲取定位,兩個重載分別以 PendingIntent 和 LocationListener 接收結果。它是定位方式的抽象表示,能查詢精度、名稱、耗電需求、是否收費,以及是否需要基站、網絡、衛星,是否支持海拔、方位、速度等信息。
位置信息本體,常用取值方法:getAccuracy()、getAltitude()、getBearing()、getLatitude()、getLongitude()、getProvider()、getSpeed(),以及 hasAccuracy() 這類存在性判斷。
取 Provider 時的篩選條件類:setAccuracy()、setAltitudeRequired()、setBearingRequired()、setCostAllowed()、setPowerRequirement()、setSpeedRequired()。

可以看到設備上通常有三個 Provider:
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<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
btn_one = findViewById(R.id.btn_one);
btn_two = findViewById(R.id.btn_two);
btn_three = findViewById(R.id.btn_three);
tv_result = 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();
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);
break;
case R.id.btn_three: // 指定名稱
pNames.clear();
pNames.add(lm.getProvider(LocationManager.GPS_PROVIDER).getName());
break;
}
tv_result.setText(getProvider());
}
private String getProvider() {
StringBuilder sb = new StringBuilder();
for (String s : pNames) {
sb.append(s).append("\n");
}
return sb.toString();
}
}
定位前的第一件事,是確認 GPS 是否可用(這裡暫不討論 AGPS)。
private boolean isGpsAble(LocationManager lm) {
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
若未開啟,有兩種處理方式:
方式一:直接幫用戶打開(僅 Android 5.0 之前有效)
// 強制打開 GPS,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 即可。
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 = findViewById(R.id.tv_show);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!isGpsAble(lm)) {
Toast.makeText(this, "請打開GPS~", Toast.LENGTH_SHORT).show();
openGPS2();
}
// 先取一次最近位置
updateShow(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER));
// 每 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());
}
}
GPS 需要室外天空視野,於是趁機出門買了杯奶茶順道截圖:

關於 requestLocationUpdates(provider, minTime, minDistance, listener):當時間超過 minTime(毫秒)或位移超過 minDistance(米)時回調。minTime 建議不低於 60000(1 分鐘),更省電;若追求實時,兩者都可以給 0,但要清楚這會顯著增加功耗。
固定一個圓心,當設備進入或離開指定半徑時觸發相應處理:
addProximityAlert(double latitude, double longitude, float radius, long expiration, PendingIntent intent)
其中 expiration 為過期時間(-1 表示永不過期),intent 指定觸發時要送達的組件。
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);
}
}
配套的廣播接收者:
public class ProximityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean isEnter = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false);
Toast.makeText(context, isEnter ? "你已到達南軟B1棟附近" : "你已離開南軟B1棟附近",
Toast.LENGTH_LONG).show();
}
}
記得在清單文件中註冊 <receiver android:name=".ProximityReceiver" />。

實測時把半徑設成了 10 米,結果從 B1 走到 D1 都還沒觸發,只好冒雨多走兩圈……

Android Activity 基礎全解:從生命周期到狀態保存
一、Activity 簡介Activity 是一種應用組件,用戶可以與它所提供的屏幕進行交互,從而完成撥打電話、拍攝照片、發送郵件或查看地圖等操作。每個 Activity
IIS 怎麼加上自訂 MIME 類型?以 apk、ipa 為例
在 IIS 7 中,預設的 MIME 類型並不包含所有的副檔名,像是現在很常見的 apk、ipa 安裝檔,都需要手動補上,否則用戶下載時可能會遇到無法正確處理的問題。 具
Android 自定義標題欄的兩種做法與踩坑記錄
默認的標題欄往往不合設計稿要求——高度、背景色、按鈕位置全都不對。這時候有兩條路:一是改系統標題欄的樣式,二是乾脆不要系統標題欄,自己在佈局裡畫一個。本文兩種都試了,也踩
Android 開發環境變量配置圖文教學
無論使用 ADT 還是 Android Studio 開發,都需要先下載 JDK(官網 https://www.oracle.com/index.html)。安裝完成後,