編輯:關於 Android 開發
官方 API 文檔:LocationManager。這是系統服務,不能直接 new,需要透過 getSystemService 取得:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
另外用 GPS 定位別忘了加權限:
取得 LocationManager 物件後,可以呼叫下列常用方法:
addGpsStatusListener(GpsStatus.Listener listener):添加一個 GPS 狀態監聽器
addProximityAlert(double latitude, double longitude, float radius, long expiration, PendingIntent intent):添加一個臨界警告
getAllProviders():取得所有的 LocationProvider 列表
getBestProvider(Criteria criteria, boolean enabledOnly):根據指定條件返回最優 LocationProvider
getGpsStatus(GpsStatus status):取得 GPS 狀態
getLastKnownLocation(String provider):根據 LocationProvider 取得最近一次已知的 Location
getProvider(String name):根據名稱取得 LocationProvider
getProviders(boolean enabledOnly):取得所有可用的 LocationProvider
getProviders(Criteria criteria, boolean enabledOnly):根據指定條件取得滿足條件的所有 LocationProvider
isProviderEnabled(String provider):判斷指定名稱的 LocationProvider 是否可用
removeGpsStatusListener(GpsStatus.Listener listener):刪除 GPS 狀態監聽器
removeProximityAlert(PendingIntent intent):刪除一個臨近警告
requestLocationUpdates(long minTime, float minDistance, Criteria criteria, PendingIntent intent):透過指定的 LocationProvider 週期性地取得定位資訊,並透過 Intent 啟動相應的元件
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener):透過指定的 LocationProvider 週期性地取得定位資訊,並觸發 listener 所對應的觸發器
官方 API 文檔:LocationProvider。這是 GPS 定位元件的抽象表示,呼叫下述方法可以取得該定位元件的相關資訊。常用方法如下:
getAccuracy():返回 LocationProvider 精度
getName():返回 LocationProvider 名稱
getPowerRequirement():取得 LocationProvider 的電源需求
hasMonetaryCost():返回該 LocationProvider 是收費還是免費
meetsCriteria(Criteria criteria):判斷 LocationProvider 是否滿足 Criteria 條件
requiresCell():判斷 LocationProvider 是否需要訪問網路基站
requiresNetwork():判斷 LocationProvider 是否需要訪問網路數據
requiresSatellite():判斷 LocationProvider 是否需要訪問基於衛星的定位系統
supportsAltitude():判斷 LocationProvider 是否支援高度資訊
supportsBearing():判斷 LocationProvider 是否支援方向資訊
supportsSpeed():判斷 LocationProvider 是否支援速度資訊
官方 API 文檔:Location。位置資訊的抽象類,我們可以呼叫下述方法取得相關的定位資訊。常用方法如下:
float getAccuracy():取得定位資訊的精度
double getAltitude():取得定位資訊的高度
float getBearing():取得定位資訊的方向
double getLatitude():取得定位資訊的緯度
double getLongitude():取得定位資訊的經度
String getProvider():取得提供該定位資訊的 LocationProvider
float getSpeed():取得定位資訊的速度
boolean hasAccuracy():判斷該定位資訊是否含有精度資訊
官方 API 文檔:Criteria。取得 LocationProvider 時,可以透過這個類別設置過濾條件。常用方法如下:
setAccuracy(int accuracy):設置對的精度要求
setAltitudeRequired(boolean altitudeRequired):設置是否要求 LocationProvider 能提供高度資訊
setBearingRequired(boolean bearingRequired):設置是否要求 LocationProvider 能提供方向資訊
setCostAllowed(boolean costAllowed):設置是否要求免費
setPowerRequirement(int level):設置要求 LocationProvider 的耗電量
setSpeedRequired(boolean speedRequired):設置是否要求 LocationProvider 能提供速度資訊
執行效果圖:

由圖可以看到,當前可用的 LocationProvider 有三個,分別是:
passive:被動提供,由其他程式提供
gps:透過 GPS 取得定位資訊
network:透過網路取得定位資訊
實現代碼:
佈局檔 activity_main.xml:
MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button btn_one; private Button btn_two; private Button btn_three; private TextView tv_result; private LocationManager lm; private List pNames = new ArrayList(); // 存放LocationProvider名稱的集合 @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 + ); } return sb.toString(); } }
在使用 GPS 定位前的第一件事,應該是判斷 GPS 是否已經打開或可用;若沒打開,我們需要去開啟 GPS 才能完成定位。這裡不考慮 AGPS 的情況。
private boolean isGpsAble(LocationManager lm){ return lm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)?true:false; }
方法一:強制打開 GPS(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(android.intent.category.ALTERNATIVE); gpsIntent.setData(Uri.parse(custom:3)); try { PendingIntent.getBroadcast(LocationActivity.this, 0, gpsIntent, 0).send(); } catch (PendingIntent.CanceledException e) { e.printStackTrace(); } }
方法二:打開 GPS 位置資訊設置頁面,讓使用者自行開啟。
//打開位置信息設置頁面讓用戶自己設置 private void openGPS2(){ Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(intent,0); }
這個非常簡單,呼叫 requestLocationUpdates 方法設定一個 LocationListener 定時檢測位置即可。示例代碼如下:
佈局 activity_location.xml:
LocationActivity.java:
/** * Created by Jay on 2015/11/20 0020. */ 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(LocationActivity.this, 請打開GPS~, Toast.LENGTH_SHORT).show(); openGPS2(); } //從GPS獲取最近的定位信息 Location lc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); updateShow(lc); //設置間隔兩秒獲得一次GPS定位信息 lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 8, new LocationListener() { @Override public void onLocationChanged(Location location) { // 當GPS定位信息發生改變時,更新定位 updateShow(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { // 當GPS LocationProvider可用時,更新定位 updateShow(lm.getLastKnownLocation(provider)); } @Override public void onProviderDisabled(String provider) { updateShow(null); } }); } //定義一個更新顯示的方法 private void updateShow(Location location) { if (location != null) { StringBuilder sb = new StringBuilder(); sb.append(當前的位置信息: ); sb.append(精度: + location.getLongitude() + ); sb.append(緯度: + location.getLatitude() + ); sb.append(高度: + location.getAltitude() + ); sb.append(速度: + location.getSpeed() + ); sb.append(方向: + location.getBearing() + ); sb.append(定位精度: + location.getAccuracy() + ); tv_show.setText(sb.toString()); } else tv_show.setText(); } private boolean isGpsAble(LocationManager lm) { return lm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER) ? true : false; } //打開設置頁面讓用戶自己設置 private void openGPS2() { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(intent, 0); } }
因為 GPS 需要在室外才能用,於是趁著這個機會到外面實際測試並截圖:

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener):當時間超過 minTime(單位:毫秒),或位置移動超過 minDistance(單位:米),就會呼叫 listener 中的方法更新 GPS 資訊。建議 minTime 不小於 60000,即 1 分鐘,這樣會更加高效而且省電;若你需要盡可能即時地更新 GPS,可將 minTime 和 minDistance 設為 0。
對了,別忘了你還需要一枚權限:
就是固定一個點,當手機與該點的距離少於指定範圍時,可以觸發對應的處理,有點像地理圍欄。我們可以呼叫 LocationManager 的 addProximityAlert 方法添加臨近警告。完整方法如下:
latitude:指定固定點的緯度
addProximityAlert(double latitude, double longitude, float radius, long expiration, PendingIntent intent)
屬性說明:
longitude:指定固定點的經度
radius:指定半徑長度
expiration:指定經過多少毫秒後該臨近警告就會過期失效,-1 表示永不過期
intent:該參數指定臨近該固定點時觸發該 intent 對應的元件
示例代碼如下:
ProximityActivity.java:
/** * Created by Jay on 2015/11/21 0021. */ 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:
/** * Created by Jay on 2015/11/21 0021. */ 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(); } }
別忘了在 AndroidManifest.xml 中註冊:
執行效果圖:(設置了 10m 範圍,實際走到一定距離外才觸發提醒)


用開源框架 PagerSlidingTabStrip 做 Android 頂部導航
開源框架官網:https://github.com/astuetz/PagerSlidingTabStrip它可以理解為搭配 ViewPager 使用的「互動式頁面指示器
Material Design 實作:用 TextInputLayout 做出浮動標籤與錯誤提示
上一篇談完了 NavigationView,這次要說的是表單裡最容易被低估的一個小元件:TextInputLayout。 它解決了什麼問題 TextInputLayou
機頂盒 GridView 與 ScrollView 焦點滾動方案
機頂盒 GridView 與 ScrollView 焦點滾動方案 在機頂盒或電視類應用中,焦點操作與手機觸控有明顯差異。開發者常會遇到 GridView 的子項目需要取得
百度地圖 API 顯示當前位置
百度地圖 API 顯示當前位置使用百度地圖顯示定位,需要下載 SDK、加入 jar 與 so 檔案,並在 AndroidManifest.xml 設定 API Key、定