Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 四大組件收官:Service 初體驗(啟動、綁定與前台服務)

編輯:關於 Android 開發

Android 四大組件收官:Service 初體驗(啟動、綁定與前台服務)

終於走到 Service 了。從年前搭環境開始,到現在把四大組件學完,前後花了三週——期間除了除夕和初一,每天堅持啃下一個知識點,照著《第一行代碼》把示例都敲了一遍,確實受益匪淺。接著要往其他方向繼續拓展,先把 Service 這一章好好收尾。

顧名思義,Service 就是「服務」,用來為應用提供後台能力。比如聽歌的同時还想下載,這種事交給 Service 就很合適;音樂在後台持續播放,也是一個服務。廢話不多說,新建工程 ServiceTest,先寫布局:兩個按鈕,一個啟動、一個停止。

 <!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--> <linearlayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="10dp" android:padding="10dp" tools:context="com.example.jared.servicetest.MainActivity"><button android:id="@+id/startService" android:text="啟動Service" android:layout_width="match_parent" android:layout_height="wrap_content" android:textallcaps="false"></button><button android:id="@+id/stopService" android:text="停止Service" android:layout_width="match_parent" android:layout_height="wrap_content" android:textallcaps="false"></button></linearlayout>

接著新建 MyService 繼承 Service,重寫生命週期中幾個關鍵方法,並在各處埋一點日誌和 Toast,方便觀察調用時序:

 package com.example.jared.servicetest; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; /** * Created by jared on 16/2/18. */ public class MyService extends Service{ private static final String TAG = "MyService"; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate is called"); Toast.makeText(MyService.this, "onCreate is called",Toast.LENGTH_SHORT).show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand is called"); Toast.makeText(MyService.this, "onStartCommand is called",Toast.LENGTH_SHORT).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy is called"); Toast.makeText(MyService.this, "onDestroy is called",Toast.LENGTH_SHORT).show(); } }

MainActivity 中把兩個按鈕分別綁定 startService 與 stopService:

 package com.example.jared.servicetest; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button mStartServiceBtn; private Button mStopServiceBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mStartServiceBtn = (Button)findViewById(R.id.startService); mStopServiceBtn = (Button)findViewById(R.id.stopService); mStartServiceBtn.setOnClickListener(new myOnClickListener()); mStopServiceBtn.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()) { case R.id.startService: Intent mStartIntent = new Intent(getApplicationContext(), MyService.class); startService(mStartIntent); break; case R.id.stopService: Intent mSopIntent = new Intent(getApplicationContext(), MyService.class); stopService(mSopIntent); break; default: break; } } } } 

先運行看看啟動效果:


 

可以看到先走了 onCreate,再走 onStartCommand。此時打開系統設置 → 應用 → 運行中,能查到 ServiceTest 已經在跑:

值得注意的是,服務已在運行時,再次點擊「啟動 Service」不會重複調用 onCreate,只會再走一次 onStartCommand;只有先 stop 之後重新啟動,才會重新經歷完整的生命週期。stop 時調用的是 onDestroy:

用 onBind 讓 Activity 與 Service 通話

上面那個 onBind 返回 null,相當於不支持綁定。如果希望 Activity 能直接調用 Service 裡的方法(例如查詢下載進度),就需要通過 Binder 打開這條通道。先擴充布局,加入綁定與解綁按鈕:

 <!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--> <linearlayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="10dp" android:padding="10dp" tools:context="com.example.jared.servicetest.MainActivity"><button android:id="@+id/startService" android:text="啟動Service" android:layout_width="match_parent" android:layout_height="wrap_content" android:textallcaps="false"></button><button android:id="@+id/stopService" android:text="停止Service" android:layout_width="match_parent" android:layout_height="wrap_content" android:textallcaps="false"></button><button android:id="@+id/startDownloadService" android:text="綁定Service Download" android:layout_width="match_parent" android:layout_height="wrap_content" android:textallcaps="false"></button><button android:id="@+id/stopDownloadService" android:text="解綁Service Download" android:layout_width="match_parent" android:layout_height="wrap_content" android:textallcaps="false"></button><button android:id="@+id/startGetProgressService" android:text="綁定Service GetProgress" android:layout_width="match_parent" android:layout_height="wrap_content" android:textallcaps="false"></button><button android:id="@+id/stopGetProgressService" android:text="解綁Service GetProgress" android:layout_width="match_parent" android:layout_height="wrap_content" android:textallcaps="false"></button></linearlayout>

Service 內部定義一個 DownloadBinder,模擬下載:啟動後開線程每秒把進度加一,並對外暴露 getProgress 供查詢。

 package com.example.jared.servicetest; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; /** * Created by jared on 16/2/18. */ public class MyService extends Service{ private static final String TAG = "MyService"; private DownloadBinder mDownloadBinder = new DownloadBinder(); class DownloadBinder extends Binder { private int progress = 0; public void startDownload() { Log.d(TAG, "startDownload is called"); Toast.makeText(MyService.this, "startDownload is called",Toast.LENGTH_SHORT).show(); progress = 0; new Thread(new Runnable(){ @Override public void run() { for (int i=0; i<=100; i++) { try { Thread.sleep(1000); progress++; } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } public int getProgress() { Log.d(TAG, "getProgress is called"); Toast.makeText(MyService.this, "getProgress is called",Toast.LENGTH_SHORT).show(); return progress; } } @Nullable @Override public IBinder onBind(Intent intent) { return mDownloadBinder; } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate is called"); Toast.makeText(MyService.this, "onCreate is called",Toast.LENGTH_SHORT).show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand is called"); Toast.makeText(MyService.this, "onStartCommand is called",Toast.LENGTH_SHORT).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy is called"); Toast.makeText(MyService.this, "onDestroy is called",Toast.LENGTH_SHORT).show(); } } 

Activity 這邊通過 ServiceConnection 接上 Binder:綁定成功後 onServiceConnected 會拿到 DownloadBinder,於是就能直接調用 startDownload 與 getProgress。

 package com.example.jared.servicetest; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Button mStartServiceBtn; private Button mStopServiceBtn; private Button mBindService1Btn; private Button mUnbindService1Btn; private Button mBindService2Btn; private Button mUnbindService2Btn; private MyService.DownloadBinder downloadBinder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mStartServiceBtn = (Button)findViewById(R.id.startService); mStopServiceBtn = (Button)findViewById(R.id.stopService); mBindService1Btn = (Button)findViewById(R.id.startDownloadService); mUnbindService1Btn = (Button)findViewById(R.id.stopDownloadService); mBindService2Btn = (Button)findViewById(R.id.startGetProgressService); mUnbindService2Btn = (Button)findViewById(R.id.stopGetProgressService); mStartServiceBtn.setOnClickListener(new myOnClickListener()); mStopServiceBtn.setOnClickListener(new myOnClickListener()); mBindService1Btn.setOnClickListener(new myOnClickListener()); mUnbindService1Btn.setOnClickListener(new myOnClickListener()); mBindService2Btn.setOnClickListener(new myOnClickListener()); mUnbindService2Btn.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()) { case R.id.startService: Intent mStartIntent = new Intent(getApplicationContext(), MyService.class); startService(mStartIntent); break; case R.id.stopService: Intent mSopIntent = new Intent(getApplicationContext(), MyService.class); stopService(mSopIntent); break; case R.id.startDownloadService: Intent mBindIntent = new Intent(getApplicationContext(), MyService.class); bindService(mBindIntent, startDownloadInService, BIND_AUTO_CREATE); break; case R.id.stopDownloadService: unbindService(startDownloadInService); break; case R.id.startGetProgressService: Intent mGetProgress = new Intent(getApplicationContext(), MyService.class); bindService(mGetProgress, getProgressInService, BIND_AUTO_CREATE); break; case R.id.stopGetProgressService: unbindService(getProgressInService); break; default: break; } } } private ServiceConnection startDownloadInService = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { downloadBinder = (MyService.DownloadBinder)iBinder; downloadBinder.startDownload(); } @Override public void onServiceDisconnected(ComponentName componentName) { } }; private ServiceConnection getProgressInService = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { downloadBinder = (MyService.DownloadBinder)iBinder; String progressValue = String.valueOf(downloadBinder.getProgress()); Toast.makeText(getApplicationContext(), "ProgressNow is:"+progressValue, Toast.LENGTH_SHORT).show(); } @Override public void onServiceDisconnected(ComponentName componentName) { } }; }

先啟動下載,再查進度,運行效果如下:

這裡有幾個容易踩的坑:Service 默認是「單例式」的,同一進程內只有一個實例。通過 bindService 綁定時會觸發 onCreate,全部解綁後才會走 onDestroy。另外,查進度這種一次性調用完必須解綁,否則下一次綁定拿到的仍是舊的 ServiceConnection,查詢會失效;如果既調用了 startService 又調用了 bindService,那 stopService 和 unbindService 兩邊都得執行,服務才會真正銷毀。

前台服務:讓 Service 不被輕易回收

系統內存緊張時會回收優先級較低的後台服務。若希望某些任務(例如音樂播放、文件下載)穩定存活,就需要把它提升為前台服務——它會一直在通知欄保留一條可點擊的通知,讓用戶清楚感知到「有東西正在運行」。改動很小,只是在 onCreate 中構建通知並調用 startForeground:

 package com.example.jared.servicetest; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; /** * Created by jared on 16/2/18. */ public class MyService extends Service{ private static final String TAG = "MyService"; private static final int NOTIFICATION_ID = 1; private DownloadBinder mDownloadBinder = new DownloadBinder(); class DownloadBinder extends Binder { private int progress = 0; public void startDownload() { Log.d(TAG, "startDownload is called"); Toast.makeText(MyService.this, "startDownload is called",Toast.LENGTH_SHORT).show(); progress = 0; new Thread(new Runnable(){ @Override public void run() { for (int i=0; i<=100; i++) { try { Thread.sleep(1000); progress++; } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } public int getProgress() { Log.d(TAG, "getProgress is called"); Toast.makeText(MyService.this, "getProgress is called",Toast.LENGTH_SHORT).show(); return progress; } } @Nullable @Override public IBinder onBind(Intent intent) { return mDownloadBinder; } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate is called"); Toast.makeText(MyService.this, "onCreate is called",Toast.LENGTH_SHORT).show(); NotificationCompat.Builder notification = new NotificationCompat.Builder(this); notification.setSmallIcon(R.mipmap.ic_launcher); notification.setContentTitle("前台服務"); notification.setContentText("這是個前台服務"); Intent intent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); notification.setContentIntent(pendingIntent); startForeground(NOTIFICATION_ID, notification.build()); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand is called"); Toast.makeText(MyService.this, "onStartCommand is called",Toast.LENGTH_SHORT).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy is called"); Toast.makeText(MyService.this, "onDestroy is called",Toast.LENGTH_SHORT).show(); stopForeground(true); } }

運行後可以看到通知欄多了一條常駐提示:

Activity 退出後它依然存在,只有停止服務才會消失,點擊通知還能回到 App——這正是音樂播放器退出界面後仍在放歌的原理。要注意的是,較新版本的 Android 對前台服務提出了更嚴格的要求:需要聲明對應的 foregroundServiceType 權限,並在通知渠道(NotificationChannel)上正確配置,否則在 Android 8.0 以上會直接拋出異常。

Service 就先學到這裡。四大組件至此全部過了一遍,接著繼續往其他知識點推進。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved