編輯:關於 Android 程式設計
獲取用戶所在城市通常分為兩個步驟:先取得當前位置的經度與緯度,再根據經緯度轉換為城市名稱。本文將逐步說明。
使用 GPS 前需在清單文件中加入定位權限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
先判斷 GPS 模塊是否可用,若未開啟則引導用戶前往設置頁開啟:
private void openGPSSettings() {
LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS 模塊正常", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(this, "請開啟 GPS!", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(Settings.ACTION_SECURITY_SETTINGS), 0);
}
通過 Criteria 選擇合適的定位提供者,再讀取位置並註冊監聽器以實時更新:
private void getLocation() {
LocationManager locationManager =
(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateToNewLocation(location);
locationManager.requestLocationUpdates(provider, 100 * 1000, 500, locationListener);
}
private void updateToNewLocation(Location location) {
TextView tv1 = (TextView) this.findViewById(R.id.tv1);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
tv1.setText("維度:" + latitude + "\n經度:" + longitude);
} else {
tv1.setText("無法獲取地理信息");
}
}
經緯度轉城市名稱需要依賴地圖服務,目前主要有百度地圖與谷歌地圖兩種選擇。百度地圖需註冊賬號並申請 APP_KEY,谷歌地圖可直接調用。
百度地圖接口:
https://api.map.baidu.com/geocoder?output=json&location=緯度,經度&key=APP_KEY
谷歌地圖接口:
https://maps.google.com/maps/api/geocode/json?latlng=緯度,經度&language=zh-CN&sensor=true
兩者都支持返回 JSON 或 XML 格式。以百度返回的 JSON 為例,其中 addressComponent 字段就包含了省、市、區、街道等結構化信息:
{
"status": "OK",
"result": {
"formatted_address": "河南省洛陽市嵩縣洛欏線",
"addressComponent": {
"city": "洛陽市",
"district": "嵩縣",
"province": "河南省",
"street": "洛欏線"
},
"cityCode": 153
}
}
而谷歌返回的 JSON 則把各級行政信息放在 results 數組的 address_components 中,並以 types 標明其類型(如 locality 表示城市、administrative_area_level_1 表示省份等),解析時按需選取即可。
Android 自定義 ScrollView 與 ListView:縱向滑動需求全攻略
1、概述 群裡一位朋友有個需求:實現循環滑動,且每次滑動結束時保持每個 Item 完整顯示。當時我給他寫了個 Demo,所有代碼都塞在 Activity 裡,後期看來實在
Android 拍照與相冊封裝實戰:告別崩潰、空白與圖片方向錯亂
項目下載地址:https://github.com/Aiushtha/android-PictureSelector 最早使用 Android 調用系統拍照時,我遇到了各
用 Java 從零實作 DES 加密:原理與程式碼完整整理
DES(Data Encryption Standard)是早期最經典的分組加密演算法之一。本文以 Java 為例,把 DES 的每個關鍵環節——從初始置換、密鑰擴展、S
自定義 View 實作水波紋效果
效果一:遮罩式水波紋 第一種效果的核心,是把波紋圖與圓形遮罩圖結合,利用 PorterDuff 的 DST_IN 模式,只保留兩者交集的下半部分,讓水波看起來像是在圓形區