編輯:關於 Android 程式設計
本案例研究探討如何將地圖與地理定位功能建構到 Android 商務應用之中,包含在 Google Maps 上覆蓋店家位置,以及當裝置進入店家的地理圍欄鄰近區域時,透過地理圍欄主動通知使用者。
在本案例研究中,我們將把地圖與地理定位功能整合到一款以 Android 平板電腦為基礎的餐廳商務應用裡(圖 1)。使用者可以從主選單中的「位置與地理圍欄」項目進入地理定位功能(圖 2)。

圖 1 餐廳應用的主介面

圖 2 彈出式選單項目
Google Maps Android API v2
Google Maps Android API v2 是 Google Play 服務的一部分。若要使用這套 API,必須先透過 Google Play 服務 SDK Manager 下載 Google Play 服務套件;接著在 Google APIs 主控台申請並取得 API 金鑰,最後將 Google Play 服務的 SDK 參照加入 AndroidManifest.xml 之中。

圖 3 餐廳應用在 Google 地圖上顯示店家的位置。
為了使用 Google Maps Android API v2,需要在
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- The following two permissions are not required to use
Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
程式碼示例 1。使用 Google Maps Android API 時建議指定的權限(其中 ACCESS_MOCK_LOCATION 僅在需要使用模擬位置測試應用時才加入)。
此外,我們還必須在
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="copy your API Key here" />
程式碼示例 2。指定 Google Play 服務版本與 API 金鑰。
首先,在你的 Activity 版面配置 XML 檔中,加入一個 MapFragment 元素(程式碼示例 3)。
<fragment
android:id="@+id/storelocationmap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:name="com.google.android.gms.maps.MapFragment" />
程式碼示例 3。在 Activity 版面配置中加入 MapFragment。
接著在你的 Activity 類別中,可以取得 Google Maps 的 MapFragment 物件,並在每一個店家位置上繪製店家圖示:
…
private static final LatLng CHANDLER = new LatLng(33.455,-112.0668);
…
private static final StoreLocation[] ALLRESTURANTLOCATIONS = new StoreLocation[] {
new StoreLocation(new LatLng(33.455,-112.0668), new String("Phoenix, AZ")),
new StoreLocation(new LatLng(33.5123,-111.9336), new String("SCOTTSDALE, AZ")),
new StoreLocation(new LatLng(33.3333,-111.8335), new String("Chandler, AZ")),
new StoreLocation(new LatLng(33.4296,-111.9436), new String("Tempe, AZ")),
new StoreLocation(new LatLng(33.4152,-111.8315), new String("Mesa, AZ")),
new StoreLocation(new LatLng(33.3525,-111.7896), new String("Gilbert, AZ"))
};
…
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geolocation_view);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.storelocationmap)).getMap();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CHANDLER, ZOOM_LEVEL));
Drawable iconDrawable = getResources().getDrawable(R.drawable.ic_launcher);
Bitmap iconBmp = ((BitmapDrawable) iconDrawable).getBitmap();
for(int ix = 0; ix < ALLRESTURANTLOCATIONS.length; ix++) {
mMap.addMarker(new MarkerOptions()
.position(ALLRESTURANTLOCATIONS[ix].mLatLng)
.icon(BitmapDescriptorFactory.fromBitmap(iconBmp)));
}
…
程式碼示例 4。在 Google Maps 上繪製店家圖示。
地理圍欄是一個圓形區域,由某個點的經緯度座標與半徑共同決定。Android 應用可以向 Android 位置服務註冊地理圍欄,並指定其有效期限。每當地理圍欄狀態切換時——例如當 Android 裝置進入或離開已註冊的地理圍欄——位置服務都會即時通知應用。
在我們的餐廳應用裡,可以為每一個店家位置定義地理圍欄。當裝置進入店家附近時,應用便會發送一則通知,例如「您已進入最喜愛的餐廳附近!」(圖 4)。

圖 4 我們依據興趣點與半徑,將地理圍欄定義為一個圓形範圍。
在 Android SDK 中,位置服務同樣是 Google Play 服務 APK 的一部分,位於「Extras」目錄底下。
若要申請地理圍欄監控,首先必須在應用的清單檔中指定 ACCESS_FINE_LOCATION 權限(這在上一節已完成)。此外,還需要檢查 Google Play 服務的可用性(程式碼示例 5 中的 checkGooglePlayServices() 方法)。當 locationClient().connect() 呼叫與位置客戶端成功建立連線後,位置服務會回呼 onConnected(Bundle bundle) 函式,位置客戶端便能透過它來申請新增或刪除地理圍欄。
public class GeolocationActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks
{
…
private LocationClient mLocationClient;
…
static class StoreLocation {
public LatLng mLatLng;
public String mId;
StoreLocation(LatLng latlng, String id) {
mLatLng = latlng;
mId = id;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geolocation_view);
mLocationClient = new LocationClient(this, this, this);
// Create a new broadcast receiver to receive updates from the listeners and service
mGeofenceBroadcastReceiver = new ResturantGeofenceReceiver();
// Create an intent filter for the broadcast receiver
mIntentFilter = new IntentFilter();
// Action for broadcast Intents that report successful addition of geofences
mIntentFilter.addAction(ACTION_GEOFENCES_ADDED);
// Action for broadcast Intents that report successful removal of geofences
mIntentFilter.addAction(ACTION_GEOFENCES_REMOVED);
// Action for broadcast Intents containing various types of geofencing errors
mIntentFilter.addAction(ACTION_GEOFENCE_ERROR);
// All Location Services sample apps use this category
mIntentFilter.addCategory(CATEGORY_LOCATION_SERVICES);
createGeofences();
mRegisterGeofenceButton = (Button)findViewById(R.id.geofence_switch);
mGeofenceState = CAN_START_GEOFENCE;
}
@Override
protected void onResume() {
super.onResume();
// Register the broadcast receiver to receive status updates
LocalBroadcastManager.getInstance(this).registerReceiver(
mGeofenceBroadcastReceiver, mIntentFilter);
}
/**
* Create a Geofence list
*/
public void createGeofences() {
for(int ix=0; ix < ALLRESTURANTLOCATIONS.length; ix++) {
Geofence fence = new Geofence.Builder()
.setRequestId(ALLRESTURANTLOCATIONS[ix].mId)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.setCircularRegion(
ALLRESTURANTLOCATIONS[ix].mLatLng.latitude, ALLRESTURANTLOCATIONS[ix].mLatLng.longitude, GEOFENCERADIUS)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
mGeofenceList.add(fence);
}
}
// callback function when the mRegisterGeofenceButton is clicked
public void onRegisterGeofenceButtonClick(View view) {
if (mGeofenceState == CAN_REGISTER_GEOFENCE) {
registerGeofences();
mGeofenceState = GEOFENCE_REGISTERED;
mGeofenceButton.setText(R.string.unregister_geofence);
mGeofenceButton.setClickable(true);
}
else {
unregisterGeofences();
mGeofenceButton.setText(R.string.register_geofence);
mGeofenceButton.setClickable(true);
mGeofenceState = CAN_REGISTER_GEOFENCE;
}
}
private boolean checkGooglePlayServices() {
int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (result == ConnectionResult.SUCCESS) {
return true;
}
else {
Dialog errDialog = GooglePlayServicesUtil.getErrorDialog(
result, this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
if (errDialog != null) {
errDialog.show();
}
}
return false;
}
public void registerGeofences() {
if (!checkGooglePlayServices()) {
return;
}
mRequestType = REQUEST_TYPE.ADD;
try {
// Try to add geofences
requestConnectToLocationClient();
} catch (UnsupportedOperationException e) {
// handle the exception
}
}
public void unregisterGeofences() {
if (!checkGooglePlayServices()) {
return;
}
// Record the type of removal
mRequestType = REQUEST_TYPE.REMOVE;
// Try to make a removal request
try {
mCurrentIntent = getRequestPendingIntent();
requestConnectToLocationClient();
} catch (UnsupportedOperationException e) {
// handle the exception
}
}
public void requestConnectToLocationServices () throws UnsupportedOperationException {
// If a request is not already in progress
if (!mRequestInProgress) {
mRequestInProgress = true;
locationClient().connect();
}
else {
// Throw an exception and stop the request
throw new UnsupportedOperationException();
}
}
/**
* Get a location client and disconnect from Location Services
*/
private void requestDisconnectToLocationServices() {
// A request is no longer in progress
mRequestInProgress = false;
locationClient().disconnect();
if (mRequestType == REQUEST_TYPE.REMOVE) {
mCurrentIntent.cancel();
}
}
/**
* returns A LocationClient object
*/
private GooglePlayServicesClient locationClient() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(this, this, this);
}
return mLocationClient;
}
/*
Called back from the Location Services when the request to connect the client finishes successfully. At this point, you can
request the current location or start periodic updates
*/
@Override
public void onConnected(Bundle bundle) {
if (mRequestType == REQUEST_TYPE.ADD) {
// Create a PendingIntent for Location Services to send when a geofence transition occurs
mGeofencePendingIntent = createRequestPendingIntent();
// Send a request to add the current geofences
mLocationClient.addGeofences(mGeofenceList, mGeofencePendingIntent, this);
}
else if (mRequestType == REQUEST_TYPE.REMOVE){
mLocationClient.removeGeofences(mCurrentIntent, this);
}
…
}
程式碼示例 5。透過位置服務申請地理圍欄監控。
位置服務的申請通常是非阻斷(non-blocking)或非同步(asynchronous)的呼叫。事實上,在上一節的程式碼示例 5 中,我們已經實作了其中一個函式:locationClient().connect() 呼叫與位置客戶端建立連線後,位置服務會回呼 onConnected(Bundle bundle) 函式。程式碼示例 6 列出了我們需要另外實作的位置回呼函式。
public class GeolocationActivity extends Activity implements
OnAddGeofencesResultListener,
OnRemoveGeofencesResultListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
…
@Override
public void onDisconnected() {
mRequestInProgress = false;
mLocationClient = null;
}
/*
* Handle the result of adding the geofences
*/
@Override
public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {
// Create a broadcast Intent that notifies other components of success or failure
Intent broadcastIntent = new Intent();
// Temp storage for messages
String msg;
// If adding the geocodes was successful
if (LocationStatusCodes.SUCCESS == statusCode) {
// Create a message containing all the geofence IDs added.
msg = getString(R.string.add_geofences_result_success,
Arrays.toString(geofenceRequestIds));
// Create an Intent to broadcast to the app
broadcastIntent.setAction(ACTION_GEOFENCES_ADDED)
.addCategory(CATEGORY_LOCATION_SERVICES)
.putExtra(EXTRA_GEOFENCE_STATUS, msg);
// If adding the geofences failed
} else {
msg = getString(
R.string.add_geofences_result_failure,
statusCode,
Arrays.toString(geofenceRequestIds)
);
broadcastIntent.setAction(ACTION_GEOFENCE_ERROR)
.addCategory(CATEGORY_LOCATION_SERVICES)
.putExtra(EXTRA_GEOFENCE_STATUS, msg);
}
LocalBroadcastManager.getInstance(this)
.sendBroadcast(broadcastIntent);
// request to disconnect the location client
requestDisconnectToLocationServices();
}
/*
* Implementation of OnConnectionFailedListener.onConnectionFailed
* If a connection or disconnection request fails, report the error
* connectionResult is passed in from Location Services
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
mInProgress = false;
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (SendIntentException e) {
// log the error
}
}
else {
Intent errorBroadcastIntent = new Intent(ACTION_CONNECTION_ERROR);
errorBroadcastIntent.addCategory(CATEGORY_LOCATION_SERVICES)
.putExtra(EXTRA_CONNECTION_ERROR_CODE,
connectionResult.getErrorCode());
LocalBroadcastManager.getInstance(this)
.sendBroadcast(errorBroadcastIntent);
}
}
@Override
public void onRemoveGeofencesByPendingIntentResult(int statusCode,
PendingIntent requestIntent) {
// Create a broadcast Intent that notifies other components of success or failure
Intent broadcastIntent = new Intent();
// If removing the geofences was successful
if (statusCode == LocationStatusCodes.SUCCESS) {
// Set the action and add the result message
broadcastIntent.setAction(ACTION_GEOFENCES_REMOVED);
broadcastIntent.putExtra(EXTRA_GEOFENCE_STATUS,
getString(R.string.remove_geofences_intent_success));
}
else {
// removing the geocodes failed
// Set the action and add the result message
broadcastIntent.setAction(ACTION_GEOFENCE_ERROR);
broadcastIntent.putExtra(EXTRA_GEOFENCE_STATUS,
getString(R.string.remove_geofences_intent_failure,
statusCode));
}
LocalBroadcastManager.getInstance(this)
.sendBroadcast(broadcastIntent);
// request to disconnect the location client
requestDisconnectToLocationServices();
}
public class ResturantGeofenceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Intent contains information about errors in adding or removing geofences
if (TextUtils.equals(action, ACTION_GEOFENCE_ERROR)) {
// handleGeofenceError(context, intent);
}
else if (TextUtils.equals(action, ACTION_GEOFENCES_ADDED)
|| TextUtils.equals(action, ACTION_GEOFENCES_REMOVED)) {
// handleGeofenceStatus(context, intent);
}
else if (TextUtils.equals(action, ACTION_GEOFENCE_TRANSITION)) {
// handleGeofenceTransition(context, intent);
}
else {
// handle error
}
}
}
程式碼示例 6。位置服務相關的回呼函式實作,包含新增、移除地理圍欄的結果處理,以及狀態廣播接收器。
Activity 轉場黑科技:讓界面從指定位置裂開並向上下拉伸
需求描述Activity(或 Fragment)跳轉時,當前界面從某個指定位置「裂開」,上半部分向上滑出屏幕、下半部分向下滑出,露出後面即將展示的新界面。整體效果如下:流
Android 對話框(Dialog)完全整理:七種常見形態與源碼
Activity 為開發者提供了一套方便的對話框管理機制,透過 onCreateDialog(int)、onPrepareDialog(int, Dialog)、show
Android UI 之 FrameLayout(幀佈局)详解
FrameLayout 幀佈局介紹 幀佈局會為其中的每個元件開闢一塊空白區域(稱為「幀」),這些幀一層層疊加在一起,有點像一張張覆蓋貼上的海報,後加入的元件會把前面的元件
Android 圖片處理記憶體優化系列:圖片牆案例實作
本文要探討的核心,是圖片的記憶體快取機制,以及如何從網路非同步抓取圖片並呈現在圖片牆上。 工程效果圖如下: 以下是程式中幾個比較不常見的屬性說明(其實查一下