編輯:關於 Android 程式設計
在 Android 開發中,Service(服務)是一種專門用來在後台執行長期任務的組件,它不需要與使用者進行任何直接互動,就能默默地在背景裡運作。無論是播放音樂、下載檔案還是處理資料同步,Service 都是實現這類需求的關鍵。
Service 主要提供兩種啟動途徑,兩者在用途與行為上有明顯差異:
想真正用好 Service,以下幾點值得深入理解:
如果某個組件(例如 Activity)透過 startService() 啟動服務,就會觸發 onStartCommand(),服務隨後持續運行直到任務結束。此時停止服務需要手動控制:可以從啟動它的組件呼叫 stopService(),或在服務內部呼叫 stopSelf()。
如果是透過 bindService() 啟動,服務會一直運行,直到所有綁定的組件都解除綁定為止。
當系統記憶體吃緊時,可能會強制終止服務以釋放資源給 Activity 使用。不過有兩種情況下的服務較不容易被終止:一是服務與 Activity 處於綁定狀態,二是服務正運行於前台。即使如此,若服務最終仍被系統回收,我們也應設計好重新啟動的機制。
IntentService 是 Service 的子類別,它在處理後台任務時免去了自行開啟執行緒的麻煩,你可以直接在 onHandleIntent() 中撰寫任務邏輯,而且任務結束後會自動關閉服務。
1.... public class HelloIntentService extends IntentService { A constructor is required, and must call the super IntentService(String) constructor with a name for the worker thread. public HelloIntentService() { super("HelloIntentService"); } * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate. @Override protected void onHandleIntent(Intent intent) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. try { Thread.sleep(5000); } catch (InterruptedException e) { // Restore interrupt status. Thread.currentThread().interrupt(); } } }...
這種方式通常用於不需要與服務互動的場合。服務在 onStartCommand() 中接收傳入的 Intent:
Intent intent = new Intent(this, HelloService.class); startService(intent);
若服務沒有經過綁定,那麼 startService(intent) 中的 Intent 就是唯一的對外溝通途徑,服務通常會透過廣播向外發布結果。值得注意的是,多次啟動服務會導致 onStartCommand() 被多次呼叫。
onStartCommand() 必須回傳一個整數值,用來描述當系統殺死服務後該如何處理:
這種方式使用起來較為複雜,但也更靈活,特別適合需要與服務持續互動的情況。核心步驟是重寫 onBind() 方法並回傳 IBinder,讓其他組件能取得該物件進行通訊,整體架構頗有 client-server 的感覺,可以支援多個客戶端同時與服務溝通。
客戶端組件必須建立 ServiceConnection 來監聽與服務的連線。可以有多個客戶端連線到同一個服務,但服務的 onBind() 只會執行一次,因此分發給各客戶端的都是同一個 IBinder 物件。只有在所有客戶端都解除綁定後,服務才會被銷毀。
a. 直接繼承 Binder:這是大多數 App 常用的做法,適用於服務與 App 處於同一進程的情況,通常只用來處理後台任務。
b. 使用 Messenger:適用於需要跨進程通訊、且要求執行緒安全但非並發的場合,同一時間只能處理一個請求。它透過 Messenger 與 Handler 兩個類別完成服務與客戶端的互動,本身架構於 AIDL 之上。
服務端建立信使物件,並透過 onBind 將信使物件放進 IBinder 回傳給客戶端,客戶端便能取得服務端信使並向其發送訊息。客戶端連線後,也可以建立自己的信使物件,以訊息形式傳給服務端,讓服務端能反向回覆訊息。由於所有訊息都在同一個佇列、同一個執行緒中處理,因此天然具備執行緒安全性。
c. 使用 AIDL:適用於需要跨進程、且要能同時處理多個請求的場合。使用時需建立一個 .aidl 檔並在其中定義介面,Android SDK 工具會據此產生一個抽象類,抽象類裡再實作各種介面方法。需要注意的是,對於大多數應用而言,並不建議用 AIDL 來綁定服務,因為這會讓整體結構變得更複雜。
舉個常見場景:一個音樂播放 App 關聯了一個 Activity,Activity 啟動服務來在後台播放音樂。
服務端:
public class LocalService extends Service { // Binder given to clients private final IBinder mBinder = new LocalBinder(); // Random number generator private final Random mGenerator = new Random(); //Class used for the client Binder. Because we know this service always //runs in the same process as its clients, we don't need to deal with IPC. public class LocalBinder extends Binder { LocalService getService() { // Return this instance of LocalService so clients can call public methods return LocalService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } //method for clients public int getRandomNumber() { return mGenerator.nextInt(100); } }
客戶端:
public class BindingActivity extends Activity { LocalService mService; boolean mBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onStart() { super.onStart(); // Bind to LocalService Intent intent = new Intent(this, LocalService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } //** Called when a button is clicked (the button in the layout file attaches to // * this method with the android:onClick attribute) public void onButtonClick(View v) { if (mBound) { // Call a method from the LocalService. // However, if this call were something that might hang, then this request should // occur in a separate thread to avoid slowing down the activity performance. int num = mService.getRandomNumber(); Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show(); } } // Defines callbacks for service binding, passed to bindService() private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; }
如果只需要在 Activity 可見時與服務互動,應在 onStart() 期間綁定、onStop() 期間解除綁定。若希望 Activity 在後台停止運行時仍能接收回應,則可在 onCreate() 期間綁定、onDestroy() 期間解除綁定。但要注意,這代表 Activity 在其整個生命週期(包含後台運行期間)都會佔用服務,若服務位於其他進程,該進程被系統終止的機率也會隨之提高。
以下是一個完整的範例,客戶端與服務端透過 Messenger 通訊。
服務端 Server_Service:
package com.example.administrator.service_messenger; import android.app.Service; import android.content.Intent; import android.content.ServiceConnection; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.widget.Toast; /** * 在manifest清單文件中聲明service為另起新的進程。 */ public class Server_Service extends Service { private Messenger clientMessenger; /** * 服務端的handler */ class ServerHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case Client.MSG_FROM_CLIENT: String fromClient = msg.getData().getString("msgFromClient"); //收到來自客戶端的信息 Toast.makeText(getApplicationContext(), fromClient, Toast.LENGTH_SHORT).show(); //回復一下客戶端 Message msgFromServer = Message.obtain(null, Client.MSG_FROM_SERVER); msgFromServer.arg1 =200; try { clientMessenger.send(msgFromServer); } catch (RemoteException e) { e.printStackTrace(); } break; case Client.MSG_FROM_CLIENT_MESSE: //得到客戶端的信使對象 clientMessenger = msg.replyTo; break; } } } /** * 服務端的Messenger,使用服務端的handler做參數構造。 */ final Messenger serverMessenger = new Messenger(new ServerHandler()); /** * 我們在這裡使用服務端的信使對象serverMessenger的IBinder,將其返回給客戶端中的 * serviceConntected */ @Override public IBinder onBind(Intent intent) { Toast.makeText(getApplicationContext(), "客戶端綁定服務端成功", Toast.LENGTH_SHORT).show(); return serverMessenger.getBinder(); } @Override public void unbindService(ServiceConnection conn) { super.unbindService(conn); Toast.makeText(getApplicationContext(), "客戶端取消了服務綁定", Toast.LENGTH_SHORT).show(); } }
在 manifest 中配置:
客戶端 Client:
package com.example.administrator.service_messenger; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import java.io.UnsupportedEncodingException; import java.util.Calendar; public class Client extends AppCompatActivity { public static final int MSG_FROM_CLIENT = 1; public static final int MSG_FROM_CLIENT_MESSE = 2; public static final int MSG_FROM_SERVER = 3; //在客戶端裡拿到了服務端的信使對象 Messenger serverMessenger = null; //標記是否已經連上了服務端 boolean mBound; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_client); //綁定服務 findViewById(R.id.bt_bind).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bindService(); } }); //通過服務端的信使來發信息給服務端 findViewById(R.id.bt_send).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { sendInfoToServer(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }); //手動解綁服務 findViewById(R.id.bt_unbind).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { unBindService(); } }); } @Override protected void onDestroy() { super.onDestroy(); //在activity銷毀時,可以選擇取消綁定服務 unBindService(); } //客戶端的handler private Handler clientHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_FROM_SERVER: Toast.makeText(getApplicationContext(), "server received :"+msg.arg1+"", Toast.LENGTH_SHORT).show(); break; } } }; /** * 客戶端的Messenger,使用客戶的handler做參數構造。 */ final Messenger clientMessenger = new Messenger(clientHandler); private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { //當我們連接上服務端後,會調用該方法。在方法裡會回調給我們IBinder對象, //由於bindservice綁定服務後,服務端返回給客戶端的IBinder是同一個。 //所以這裡我們可以利用IBinder來構建服務端裡的信使對象。 //之後有了服務端的信使對象,就可以隨便網服務端發送信息了。 //構建服務端信使對象 serverMessenger = new Messenger(service); mBound = true; //並將客戶端的messenger發給服務端,讓服務端也可以給客戶端發送消息 Message msg = Message.obtain(null, MSG_FROM_CLIENT_MESSE); msg.replyTo = clientMessenger; try { serverMessenger.send(msg); } catch (RemoteException e) { e.printStackTrace(); } } public void onServiceDisconnected(ComponentName className) { // 當連接服務端異常時調用 serverMessenger = null; mBound = false; } }; private void sendInfoToServer() throws UnsupportedEncodingException { if (!mBound) return; Message msg = Message.obtain(null, MSG_FROM_CLIENT, 0, 0); String strMsg = "server received:" + Calendar.getInstance().getTime(); Bundle data = new Bundle(); data.putString("msgFromClient", strMsg); msg.setData(data); try { serverMessenger.send(msg); } catch (RemoteException e) { e.printStackTrace(); } } @Override protected void onStart() { super.onStart(); // 在界面可見時,可以選擇去綁定服務 } @Override protected void onStop() { super.onStop(); // 在界面不可見時,可以選擇去解綁服務 } private void bindService() { bindService(new Intent(this, Server_Service.class), mConnection, Context.BIND_AUTO_CREATE); } private void unBindService() { if (mBound) { unbindService(mConnection); mBound = false; } } }
當需要跨進程且能同時處理多個請求時,才會考慮使用 AIDL。由於其複雜度較高,一般應用並不需要,這裡就不再展開細節。
Android Studio 快速製作 so 的流程
在 Android 專案中,若需要整合原生程式碼,通常會需要編譯 so 動態連結庫。相較於早期手動設定 NDK,現在可透過 Android Studio 的 Native
OkHttp 框架入門實戰:Android 網路請求一篇搞定
自 Android 6.0 起,Google 移除了 HttpClient 相關 API,改用 HttpURLConnection 取代。在實際開發中,網路請求幾乎是每個
Android JNI 入門:用 C 語言實作字串加密與解密
為什麼使用 JNI 做加密 Java 層的加密邏輯容易被反編譯分析,若希望提高逆向成本,可把部分關鍵處理放到 C 語言中,再透過 JNI 與 Java 互動。這樣的架構適
自訂 View 實作:自由定製的優惠券邊緣背景
1、功能介紹 現在的購物類 App 真是多不勝數,經常能在裡面看到優惠券的身影。今天我們就來動手實作一個優惠券的背景效果。實務上若想偷懶,直接用一張背景圖當底就完工了,但