編輯:關於 Android 程式設計
近來研究了 Android 的定位方式,查閱了不少資料並實際拿手機測試,以下是我的整理。
Android 一共有三種定位方式:GPS 定位、網路定位,以及基於基站的定位。但不論採用哪一種,都需要開啟網路或 GPS。
首先在 Manifest 中加入權限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
其中 COARSE_LOCATION 用於基站定位,若缺少這個權限,在呼叫 getCellLocation() 時會報錯。
這種方式取得手機目前的基站資訊(Cell ID、LAC 等),再向 Google 的定位介面 POST 請求,換回經緯度:
public class LocationAct extends Activity {
private TextView txtInfo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btnStart);
txtInfo = (TextView) findViewById(R.id.txtInfo);
btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) { getLocation(); }
});
}
private void getLocation() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation gsmCell = (GsmCellLocation) tm.getCellLocation();
int cid = gsmCell.getCid();
int lac = gsmCell.getLac();
String netOperator = tm.getNetworkOperator();
int mcc = Integer.valueOf(netOperator.substring(0, 3));
int mnc = Integer.valueOf(netOperator.substring(3, 5));
JSONObject holder = new JSONObject();
JSONArray array = new JSONArray();
JSONObject data = new JSONObject();
try {
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
holder.put("address_language", "zh_CN");
holder.put("request_address", true);
holder.put("radio_type", "gsm");
holder.put("carrier", "HTC");
data.put("cell_id", cid);
data.put("location_area_code", lac);
data.put("mobile_country_code", mcc);
data.put("mobile_network_code", mnc);
array.put(data);
holder.put("cell_towers", array);
} catch (JSONException e) {
e.printStackTrace();
}
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://www.google.com/loc/json");
try {
httpPost.setEntity(new StringEntity(holder.toString()));
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuffer stringBuffer = new StringBuffer();
String result;
while ((result = reader.readLine()) != null) {
stringBuffer.append(result);
}
txtInfo.setText(stringBuffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}

使用 LocationManager 指定 GPS_PROVIDER,並註冊位置與 GPS 狀態監聽器:
public class MainActivity extends Activity {
private LocationManager locationManager;
private GpsStatus gpsstatus;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// 依 Criteria 取得最符合的 provider
String currentProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();
Location currentLocation = locationManager.getLastKnownLocation(currentProvider);
if (currentLocation == null) {
locationManager.requestLocationUpdates(currentProvider, 0, 0, locationListener);
}
locationManager.addGpsStatusListener(gpsListener);
// 每隔 10 秒取一次位置資訊
while (true) {
currentLocation = locationManager.getLastKnownLocation(currentProvider);
if (currentLocation != null) {
Log.d("Location", "Latitude: " + currentLocation.getLatitude());
Log.d("Location", "location: " + currentLocation.getLongitude());
break;
} else {
Log.d("Location", "Latitude: 0");
Log.d("Location", "location: 0");
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e("Location", e.getMessage());
}
}
}
private GpsStatus.Listener gpsListener = new GpsStatus.Listener() {
@Override
public void onGpsStatusChanged(int event) {
gpsstatus = locationManager.getGpsStatus(null);
switch (event) {
case GpsStatus.GPS_EVENT_FIRST_FIX: break;
case GpsStatus.GPS_EVENT_STARTED: break;
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
// 可統計目前可見的衛星數量
int count = 0;
for (GpsSatellite s : gpsstatus.getSatellites()) { count++; }
Toast.makeText(MainActivity.this, "Satellite Count:" + count, Toast.LENGTH_SHORT).show();
break;
case GpsStatus.GPS_EVENT_STOPPED:
Log.d("Location", "GPS_EVENT_STOPPED");
break;
}
}
};
private LocationListener locationListener = new LocationListener() {
@Override public void onLocationChanged(Location location) { Log.d("Location", "onLocationChanged"); }
@Override public void onProviderDisabled(String provider) { Log.d("Location", "onProviderDisabled"); }
@Override public void onProviderEnabled(String provider) { Log.d("Location", "onProviderEnabled"); }
@Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("Location", "onStatusChanged"); }
};
}

以 Criteria 描述需求,交由系統挑選最合適的 provider,並可用 Geocoder 把座標反查成地址:
package com.test;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
criteria.setSpeedRequired(false);
String currentProvider = locationManager.getBestProvider(criteria, true);
Log.d("Location", "currentProvider: " + currentProvider);
Location currentLocation = locationManager.getLastKnownLocation(currentProvider);
if (currentLocation == null) {
locationManager.requestLocationUpdates(currentProvider, 0, 0, locationListener);
}
while (true) {
currentLocation = locationManager.getLastKnownLocation(currentProvider);
if (currentLocation != null) {
Log.d("Location", "Latitude: " + currentLocation.getLatitude());
Log.d("Location", "location: " + currentLocation.getLongitude());
break;
} else {
Log.d("Location", "Latitude: 0");
Log.d("Location", "location: 0");
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e("Location", e.getMessage());
}
}
// 解析地址並顯示
Geocoder geoCoder = new Geocoder(this);
try {
int latitude = (int) currentLocation.getLatitude();
int longitude = (int) currentLocation.getLongitude();
List<Address> list = geoCoder.getFromLocation(latitude, longitude, 2);
for (int i = 0; i < list.size(); i++) {
Address address = list.get(i);
Toast.makeText(MainActivity.this,
address.getCountryName() + address.getAdminArea() + address.getFeatureName(),
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private LocationListener locationListener = new LocationListener() {
@Override public void onLocationChanged(Location location) { Log.d("Location", "onLocationChanged"); }
@Override public void onProviderDisabled(String provider) { Log.d("Location", "onProviderDisabled"); }
@Override public void onProviderEnabled(String provider) { Log.d("Location", "onProviderEnabled"); }
@Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("Location", "onStatusChanged"); }
};
}
三種方式各有取捨:GPS 精度最高但耗電、受環境影響;基站定位廣為覆蓋但精度較低;網路定位則在精度與功耗之間取得平衡,實務上常以 Criteria 交由系統自動挑選。
Android 用 ViewPager 實作左右無限循環輪播圖與底部指示點
這個範例要解決的是一個很常見的需求:輪播圖可以左右無限循環——最後一張再往右滑會回到第一張,第一張往左滑會跳到最後一張,底部並搭配指示點。先來看效果: 版面配置 &l
Android 整合訊飛語音 SDK 實現語音識別的完整流程
一、准備工作 1、你需要具備 Android 手機應用開發基礎 2、科大訊飛語音識別 SDK(Android 版) 3、科大訊飛語音識別開發 API 文檔 4、一支 An
Android 底部彈出提示框的兩種實作方式
在 Android 中,若需要從畫面底部彈出一個提示框,並搭配半透明背景與進出動畫,常見做法有兩種:使用 Activity 搭配自訂主題,或使用 PopupWindow。
Android 動畫總結:屬性動畫、補間動畫與幀動畫
動畫分類 Android 中的動畫大致分為三類: TweenAnimation(補間動畫):包含 TranslateAnimation、ScaleAnimation、Ro