編輯:關於 Android 程式設計
Service 是 Android 處理背景任務的標準答案。本文從最基礎的三個生命週期方法出發,搭配一個可實際點擊驗證的小專案,把 startService/stopService 這條路徑走通。
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 基本組件用法總結》。
ViewPager 擴展詳解:打造帶導航的 ViewPagerIndicator(含圖片快取與非同步載入)
用過 ViewPager 的人都知道,它在「橫向切換頁面」這件事上表現很好,但導航樣式的部分預設值相當陽春。GitHub 上有個很不錯的開源專案 ViewPagerInd
Android Material Design 圖形設計與圖片處理要點
格式塔原理與圖形設計 Material Design 在圖形與版面設計上,常借用格式塔心理學的觀念。格式塔強調人眼會把零散元素組織成整體,並在資訊過多時試圖簡化。因此,介
Android AutoCompleteTextView:自動提示輸入框的資料來源與設定
自動提示輸入框(AutoCompleteTextView)能明顯改善使用者體驗、縮短輸入時間——百度搜尋框就是最典型的例子。它的資料來源有兩種常見做法:從 XML 資源陣
微信「附近的人」看不到我?四個常見原因與解法
「附近的人」可以發現周邊正在使用微信的使用者,打招呼、聊天都方便。但有時會遇到一種狀況:別人搜得到其他人,卻搜不到我。這類問題通常不是故障,而是某個設定沒開或位置資訊失效