編輯:關於 Android 程式設計
startService() 只能單向派發指令,服務與使用者之間沒有來回通道。若需要讓 Activity 直接呼叫服務裡的方法並取得返回值,就必須改用 bindService()。本文示範一個本地服務(服務與存取者在同一進程)的完整實作。
客戶端要做的其實只有一件事:拿到服務回傳的 Binder 物件,再用它呼叫服務中的方法。所有複雜度都在「如何拿到」這一步。
首先自訂類別繼承 Service;接著寫一個內部類,同時繼承 Binder 並實作業務介面;最後複寫 onBind(),把該內部類的實例回傳。
這裡之所以要額外定義一個介面,是因為 Binder 內部類通常是私有成員,客戶端無法直接 new 出來接收;用介面當作共同的契約,既解決了可見性問題,也把業務邏輯抽象出來,是更規範的設計。
package cc.testservice2;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class ServiceSubclass extends Service {
private String[] names = new String[]{"小明", "小王", "小楊", "小李", "小強"};
BinderSubclass mBinderSubclass = new BinderSubclass();
@Override
public IBinder onBind(Intent intent) {
return mBinderSubclass;
}
// BinderSubclass 同時繼承 Binder 並實作業務介面
private final class BinderSubclass extends Binder implements QueryInterface {
public String queryByNumber(int number) {
return query(number);
}
}
// 服務內部的實際邏輯
public String query(int i) {
if (i > 0 && i < 6) {
return names[i - 1];
}
return "查詢錯誤,請再次輸入";
}
}
業務介面本身非常單純:
package cc.testservice2;
public interface QueryInterface {
public String queryByNumber(int number);
}
寫一個類別實作 ServiceConnection 介面;建立它的實例;呼叫 bindService() 與服務建立連線;在 onServiceConnected() 回呼中接收 Binder 物件並轉型成業務介面。
package cc.testservice2;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView mNumberTextView;
TextView mResultTextView;
Button mSearchButton;
ServiceConnectionImpl mServiceConnectionImpl;
QueryInterface mBinder;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 用於接收服務返回的 Binder 物件
mServiceConnectionImpl = new ServiceConnectionImpl();
mNumberTextView = (TextView) findViewById(R.id.numberEditText);
mResultTextView = (TextView) findViewById(R.id.resultTextView);
mSearchButton = (Button) findViewById(R.id.searchButton);
mSearchButton.setOnClickListener(new ButtonOnClickListener());
Intent intent = new Intent(this, ServiceSubclass.class);
// Activity 啟動時就建立與服務的連接
bindService(intent, mServiceConnectionImpl, this.BIND_AUTO_CREATE);
}
private class ButtonOnClickListener implements OnClickListener {
public void onClick(View v) {
String number = mNumberTextView.getText().toString();
String result = mBinder.queryByNumber(Integer.valueOf(number));
mResultTextView.setText(result);
}
}
private final class ServiceConnectionImpl implements ServiceConnection {
// 綁定成功時回呼
public void onServiceConnected(ComponentName name, IBinder service) {
mBinder = (QueryInterface) service;
}
// 解除綁定時回呼
public void onServiceDisconnected(ComponentName name) {
mBinder = null;
}
}
@Override
protected void onDestroy() {
unbindService(mServiceConnectionImpl);
super.onDestroy();
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="請輸入1到5的數字" />
<EditText
android:id="@+id/numberEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查詢" />
<TextView
android:id="@+id/resultTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
綁定與解綁必須成對。兩者用的都是同一個 ServiceConnection 實例,漏掉 unbindService() 會造成連線洩漏。
一定要複寫 onDestroy()。只在 onCreate() 建立連線卻不在 Activity 銷毀時關閉,是新手最常犯的錯誤。
onServiceConnected() 是回呼,不是同步返回。它不是呼叫 bindService() 之後立刻觸發,而是等到系統完成綁定才呼叫。因此在該回呼被執行之前,mBinder 仍是 null,若使用者手快在此刻點擊按鈕就會崩潰,實務上應加上空值判斷或先禁用按鈕。
本地服務可以直接轉型。因為 Binder 內部類本身就實作了業務介面,客戶端可直接向下轉型;但這招只在同進程有效,跨進程時收到的會是代理物件,必須改用 AIDL 的 Stub.asInterface()。
BIND_AUTO_CREATE 表示在沒有其他綁定時自動建立服務,這是最常用的旗標。另有 BIND_IMPORTANT、BIND_NOT_FOREGROUND 等,可用位元運算組合。多個客戶端可同時綁定同一個服務,系統會以第一個綁定建立它,並在最後一個解綁時銷毀它——這與 startService() 的生命週期規則完全不同,設計時別混淆。
Android 索引條實作:為 ListView 添加字母快速定位
專案需要,今天學習了一下索引的實現。 涉及的技術要點: 繪製右側的索引條 點擊某個字母,定位到 ListView 的指定位置 佈局檔案:
Google 推薦的圖片載入庫 Glide 全面解析(與 Picasso 對比)
在泰國舉辦的 Google 開發者大會上,Google 介紹了一個名為 Glide 的圖片載入庫,作者為 bumptech。這個庫已經被大量用在 Google 自家的開源
自定義View打造Android柱狀圖:橫向、縱向與比例圖三合一
做專案的時候需要一種簡單的橫向柱狀圖,翻了不少現成框架卻總覺得不合手,最後索性自己寫了一個自定義 View,順手把三種常見的柱狀圖形態都封裝進去了。 先看成果 第一種是
動手打造 Android Studio 自訂 Activity 模板
每次在 Android Studio(以下簡稱 AS)裡新增一個 Activity,只要選擇「Empty Activity」,IDE 就會自動幫你生成對應的 XML 佈局