編輯:關於 Android 程式設計
Service 是 Android 四大組件之一,它以「服務」的形式在後台運行,沒有界面,卻能承擔常駐任務。Service 本身具備優先級較高的特性,即使 Activity 被銷毀,它也不會跟著結束。不過要特別提醒:Service 默認運行在應用的主線程(UI 線程)中,並不等於「新線程」。
通過 startService() 拉起的服務一旦啟動就會持續運行,直到顯式調用 stopService() 或 stopSelf() 才會停止,與啟動它的組件是否存活無關。Service 不能啟動自己,若在服務中要跳轉到 Activity,必須聲明一個全新的任務棧(Task)。
它的生命周期非常直線:
onCreate() --> onStartCommand() --> onDestroy()
每次調用 startService() 都會再次觸發 onStartCommand()。這裡最容易踩的坑是:如果在 onStartCommand() 裡直接做耗時操作又沒有另開線程,主線程會被阻塞,甚至觸發 ANR。
bindService() 讓 Service 與調用者「綁」在一起,兩者是共存共亡的關係:調用方銷毀,服務隨之解綁並停止。它的初始化順序為:
onCreate() --> onBind() --> onServiceConnected()
這種方式的好處是調用方可以直接拿到 Service 的實例引用,像調用本地方法一樣調用服務能力。
如果客户端和服務在同一進程,最簡單的做法是自定义一個繼承 Binder 的子類,並在 onBind() 中返回它,讓客户端把 Service 實例「帶」回來。
服務端:
public class MyService extends Service {
private final LocalBinder lb = new LocalBinder();
private final Random num = new Random();
@Override
public IBinder onBind(Intent arg0) {
return lb;
}
// 本地 Binder 子類,把 Service 當前實例交給客户端
public class LocalBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
public int getRandom() {
return num.nextInt(98);
}
}
客户端通過 ServiceConnection 的 onServiceConnected() 回調拿到 Binder,再轉成 Service 實例即可:
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
LocalBinder binder = (LocalBinder) iBinder;
myService = binder.getService();
flag = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
flag = false;
}
};
記得在 onStop() 或合適的時機調用 unbindService(serviceConnection) 解除綁定,避免資源洩漏。
當服務與客户端處於不同進程時,就必须借助 AIDL(Android Interface Definition Language)。它的本質是讓系統自動生成遠程代理(Stub/Proxy),把方法調用封裝成跨進程的消息。
第一步,定義 AIDL 接口:
package com.example.service;
interface DataService {
double getData(String arg);
}
第二步,服務端實現由 AIDL 生成的 Stub:
public class MyService extends Service {
Binder binder = new DataService.Stub() {
@Override
public double getData(String arg) throws RemoteException {
if ("a".equals(arg)) {
return 1;
}
if ("b".equals(arg)) {
return 2;
}
return 0;
}
};
@Override
public IBinder onBind(Intent arg0) {
return binder;
}
}
第三步,在清單文件中聲明服務。這裡有個關鍵細節:<intent-filter> 中要寫上 AIDL 所在的包名加類名,客户端才能準確找到它。
<service android:name="com.example.android_aidl_service.MyService">
<intent-filter>
<action android:name="com.example.service.DataService" />
</intent-filter>
</service>
第四步,把 AIDL 文件所在的包原樣拷貝到客户端工程(包名必須一致),然後綁定並調用:
private DataService dataService;
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DataService.class.getName());
bindService(intent, conn, BIND_AUTO_CREATE);
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
int result = (int) dataService.getData("a");
tv.setText(result + "");
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) { }
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
dataService = DataService.Stub.asInterface(service);
}
};
這樣一來,進程間通信就完成了。
IntentService 是 Service 的子類,它把「開線程」這件事封裝了起來:內部使用工作線程串行處理傳入的 Intent,任務做完自動停止服務。開發者只需要重寫 onHandleIntent(),不需要手動管理線程,也不需要操心何時關閉服務。
它的生命周期為:
onCreate() --> onStartCommand() --> onHandleIntent() --> onDestroy()
下面是一個下載圖片並寫入 SD 卡的例子:
public class DownLoadService extends IntentService {
// 必須顯式提供帶名字的構造方法,否則會崩潰
public DownLoadService() {
super("DownLoadService");
}
@Override
protected void onHandleIntent(Intent intent) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(intent.getStringExtra("url"));
File file = new File(Environment.getExternalStorageDirectory(), "IntentService.gif");
FileOutputStream fileOutputStream = null;
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
byte[] data = EntityUtils.toByteArray(httpEntity);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data, 0, data.length);
Toast.makeText(getApplicationContext(), "下載完成", Toast.LENGTH_LONG).show();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
界面只需要一句話就能把任務交出去:
Intent intent = new Intent(MainActivity.this, DownLoadService.class);
intent.putExtra("url", url);
startService(intent);
需要長期在後台運行、由多個組件反覆觸發的任務,用 startService;需要與 Activity 緊密交互、隨界面生死的場景,用 bindService;跨進程調用,用 AIDL;而單純的串行後台任務(如下載、上傳、寫入),IntentService 是最省事的選擇。無論哪一種,都要牢記 Service 默認在主線程,耗時操作必須放到獨立線程中。
ListView 效能優化實戰:convertView 復用、圖片異步與快滑處理
前言 對做過 Android 開發的人來說,ListView 完全不陌生;而只要用過 ListView,就很難不關心它的效能。 這不只是面試的必考題(近期的幾場面試幾乎每
自製滑動開關控件 SlideSwitch:完全手繪的 iOS 風格 Switch
Android 4.0 之後官方提供了 Switch 控件,但有兩個問題:一是無法向下相容 4.0 以前的版本,在當時等於失去使用價值;二是外觀實在不算好看。 後來看到百
Android 聊天室表情與頭像功能實作
聊天室應用中,除了文字訊息,表情圖片與頭像也是常見需求。本文說明如何在 Android 中將文字中的表情標記替換成圖片,並讓聊天列表依發送者顯示不同樣式。表情替換思路表情
Android 自定義 BaseAdapter:ListView 基礎實作
ListView 與適配器 ListView 要顯示資料,通常需要 Adapter 把資料轉成每一列的 View。自定義 BaseAdapter 是最常見做法,因為它能完