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

Android Service 詳解(一):從零建立並掌握啟動與停止的生命週期

編輯:關於 Android 程式設計

Service 是 Android 處理背景任務的標準答案。本文從最基礎的三個生命週期方法出發,搭配一個可實際點擊驗證的小專案,把 startService/stopService 這條路徑走通。

一、Service 是什麼

Service 適合用來執行那些不需要使用者互動、但需要長時間存活的任務。它是 Android 四大組件之一(Activity、Service、BroadcastReceiver、ContentProvider),層級與 Activity 相當,差別在於它沒有自己的介面,只能跑在後台,卻可以與其他組件互動。

另外要牢記:Service 並非跑在獨立行程,而是依附於建立它時所屬的應用程式行程。當該行程被系統回收,依賴它的服務也會一起停止。這也是為什麼長時間任務往往還需要搭配 Foreground Service 或工作排程的原因。

二、動手實作

建立專案 TestService,先寫一個繼承 Service 的類別:

 package com.example.testservice; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } /** * 服務第一次創建的時候調用 */ @Override public void onCreate() { super.onCreate(); Toast.makeText(this, "服務的onCreate方法被調用", Toast.LENGTH_SHORT).show(); } /** * 服務每一次啟動的時候調用 */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "服務的onStartCommand方法被調用", Toast.LENGTH_SHORT).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Toast.makeText(this, "服務的onDestroy方法被調用", Toast.LENGTH_SHORT).show(); super.onDestroy(); } } 

三、別忘了註冊

新建的服務必須在 AndroidManifest.xml 中登記,否則啟動時會直接拋出例外。

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.testservice" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.testservice.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 注冊服務 --> <service android:name=".MyService"></service> </application> </manifest> 

四、版面與控制邏輯

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="啟動服務" /> <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="停止服務" /> </LinearLayout> 
 package com.example.testservice; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener{ private Button startService_Button; private Button stopService_Button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //獲取開啟服務按鈕 startService_Button = (Button) findViewById(R.id.button1); //獲取停止服務按鈕 stopService_Button = (Button) findViewById(R.id.button2); //調用點擊事件 startService_Button.setOnClickListener(this); stopService_Button.setOnClickListener(this); } /** * 點擊事件 */ @Override public void onClick(View view) { switch(view.getId()){ case R.id.button1: //"開啟服務"按鈕 Intent startIntent = new Intent(this,MyService.class); //開啟服務 startService(startIntent); break; case R.id.button2: //"停止服務"按鈕 Intent stopIntent = new Intent(this,MyService.class); //停止服務 stopService(stopIntent); break; default: break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } 

五、實測:一個容易誤解的地方

部署後的畫面:

按下「啟動服務」,會依序彈出:

 

此時若再重複按「啟動服務」,只會再彈出 onStartCommand 的提示,onCreate 不再出現。原因很單純:onCreate 僅在服務第一次被建立時呼叫一次,而 onStartCommand 每次啟動都會觸發。

按下「停止服務」:

六、流程總結

啟動:Context 的 startService → onCreate → onStartCommand → 服務運行。

停止:服務運行 → Context 的 stopService → onDestroy → 服務停止。

把這條生命週期記牢,後續不管是綁定模式、跨元件溝通還是 Foreground Service,都是在這個骨架上延伸。下一篇將談 bindService 的用法。更多內容可參考本站《Android 基本組件用法總結》。

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