編輯:關於 Android 程式設計
Service 是 Android 四大組件之一,性質近似於 Windows 中的服務:通常沒有使用者操作介面,默默運行於系統中不易被察覺。手機裡的程式更新、服務推送,背後多半都有 Service 在支撐。
Service 與 Activity 有幾分相似:都需要在 AndroidManifest.xml 中配置,生命週期也有點像。差別在於 Service 不在前台運行,而是默默在後台工作。
Service 與 Activity 一樣存在於當前行程的主線程中,因此阻塞 UI 的耗時操作不能放在 Service 裡直接執行。像是下載這類工作,必須另外開啟子線程處理;如果在 Service 中進行高 CPU 佔用或長時間操作,應用就會跳出「強制關閉還是等待」的對話框。可見 Service 與 Activity 是平級的,四大組件的地位並非浪得虛名。
Service 的生命週期分成兩條路徑:一條是 startService() 啟動後的 onCreate → onStartCommand → onDestroy;另一條是 bindService() 綁定後的 onCreate → onBind → onUnbind → onDestroy。兩條路徑都會經過 onCreate 與 onDestroy,中間環節則依啟動方式而不同。
public class BookService extends Service {
private String tag = "BookService";
@Override
public void onCreate() {
super.onCreate();
Log.i(tag, "onCreate 啟動了");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(tag, "onStartCommand 啟動了");
Toast.makeText(this, "BookService 開始了", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i(tag, "onDestroy 銷毀了");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
Log.i(tag, "onBind 綁定了");
return null;
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(tag, "onUnbind 解綁了");
return super.onUnbind(intent);
}
}
記得在 AndroidManifest.xml 中註冊:
<service android:name="com.example.googleservice.BookService"></service>
// 啟動 Intent service = new Intent(this, BookService.class); startService(service); // 停止 Intent stopservice = new Intent(this, BookService.class); stopService(stopservice);
對照 log 輸出,就能清楚看出第一條生命週期路徑的執行順序。
先定義一個繼承自 ServiceConnection 的類:
class BookServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
// 綁定 Intent binderStartIntent = new Intent(this, BookService.class); connection = new BookServiceConnection(); bindService(binderStartIntent, connection, Context.BIND_AUTO_CREATE); // 解綁 unbindService(connection);
實務上常需要 Activity 直接呼叫 Service 的方法,這時可在 BookService 中定義一個內部 Binder 類,把 Service 實例暴露出去:
class BookBinder extends Binder {
public BookService getCurrentService() {
return BookService.this;
}
}
然後在 Activity 的 onServiceConnected 中取得該實例:
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 取得 Service 實例
BookService bookService = ((BookService.BookBinder) service).getCurrentService();
// 接下來就能直接呼叫 Service 對外開放的業務方法
}
Service 長期在後台工作,可以透過 Notification 把訊息呈現到前台。修改 onCreate():
@Override
public void onCreate() {
super.onCreate();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("QQ空間")
.setContentText("有新動態,快來看看");
mNotificationManager.notify(0, mBuilder.build());
Log.i(tag, "onCreate 啟動了");
}
這樣使用者即使不在應用介面內,也能從通知列得知 Service 的工作狀態。若是長時間运行的任務(如下載、播放),進一步可改用前台服務(foreground service)搭配常駐通知,避免被系統回收。
Android 產品研發(十四):App 的升級與更新全流程
上一篇我們講了 App 中的輪詢操作,包括使用場景、作用與實作方式。輪詢通常以定時任務的形式請求伺服器並更新介面,且有明確的生命週期——在合適的頁面啟動、在特定情況下關閉
Android 權限控制實戰:自定義權限的完整實作
盼了這麼久,終於要談談如何自定義權限了,其實這個過程相當簡單。為了方便說明,我會用到兩個 App 作為示範: Permission App:用於定義一個新權限的應用。Cl
一個輕量級的 Android 網路請求框架
為什麼需要自定義請求框架 AsyncTask 雖然方便,但在複雜應用中會遇到一些限制,例如無法靈活控制線程池、也難以精細取消個別請求。當 Activity 跳轉後,先前發
MPAndroidChart 折線圖實戰:資料綁定、樣式設定與常見坑位
從資料到折線圖 本文以 MPAndroidChart 的 LineChart 為例,整理折線圖在實際專案中的資料綁定、樣式設定與常見問題。 LineChartTools