編輯:Android 技術基礎
在 Android 的世界裡,Service(服務)扮演著舉足輕重的角色。它沒有畫面,卻能在背後默默為我們播放音樂、追蹤定位、監聽來電與短信。既然 Service 如此重要,那麼如何把它「喚醒」就成了一門學問。
前面我們已經學會用 Activity 直接啟動服務,你可能會問:既然 Activity 就能搞定,為什麼還要繞道廣播?別急,等到後續我們動手做「來電監聽」「短信監聽」時,你就會明白廣播這種「一喊百應」的解耦方式有多香。本章,我們就來動手實作:如何透過一則廣播,把 Service 啟動起來。
打開 res/layout/activity_main.xml,加入一個用來發送廣播的按鈕:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="通過Broadcast啟動Service" />
</LinearLayout>
新增 src/com.genwoxue.broadcastservice/ServiceUtil.java,這是我們要被喚醒的服務本體:
package com.genwoxue.broadcastservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class ServiceUtil extends Service{
private static final String TAG="AboutService";
@Override
public IBinder onBind(Intent intent){
return null;
}
@Override
public void onCreate(){
Log.i(TAG,"服務:onCreate()");
}
//啟動
@Override
public int onStartCommand(Intent intent,int flags,int startId){
Log.i(TAG, "服務啟動:onStart()=>Intent"+intent+",startID="+startId);
return Service.START_CONTINUATION_MASK;
}
@Override
public void onDestroy(){
Log.i(TAG,"服務:onDestroy()");
}
}
接著新增 src/com.genwoxue.broadcastservice/BroadcastReceiverUtil.java,它是「收聽者」,負責辨識指定的 Action 並啟動服務:
package com.genwoxue.broadcastservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BroadcastReceiverUtil extends BroadcastReceiver{
@Override
public void onReceive(Context context,Intent intent){
//廣播接收器(接收方)判斷Action為"com.genwoxue.action.ABOUTSERVICE"則啟動服務
if("com.genwoxue.action.ABOUTSERVICE".equals(intent.getAction())){
context.startService(new Intent(context,ServiceUtil.class));
}
}
}
最後打開 src/com.genwoxue.broadcastservice/MainActivity.java,讓它負責「喊話」:
package com.genwoxue.broadcastservice;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
public class MainActivity extends Activity {
private BroadcastReceiverUtil util=null;
private Button btnSend=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend=(Button)super.findViewById(R.id.send);
btnSend.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
//發送廣播:其Action為"com.genwoxue.action.ABOUTSERVICE"
Intent intent=new Intent("com.genwoxue.action.ABOUTSERVICE");
MainActivity.this.sendBroadcast(intent);
//實例化廣播過濾器(只過濾其Action為"com.genwoxue.action.ABOUTSERVICE")
IntentFilter filter=new IntentFilter("com.genwoxue.action.ABOUTSERVICE");
//實例化廣播接收器(接收方)
util=new BroadcastReceiverUtil();
//注冊BroadcastReceiver:參數為接收器與過濾器
MainActivity.this.registerReceiver(util, filter);
}
});
}
@Override
protected void onStop(){
//停止廣播
super.unregisterReceiver(util);
super.onStop();
//停止服務
Intent intent=new Intent(MainActivity.this,ServiceUtil.class);
MainActivity.this.stopService(intent);
}
}
打開 AndroidManifest.xml,別忘了把 Service 註冊進來:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.genwoxue.broadcastservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.genwoxue.broadcastservice.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="com.genwoxue.broadcastservice.ServiceUtil" />
</application>
</manifest>
關鍵在於這一行,少了它,系統根本不認識你的服務:
<service android:name="com.genwoxue.broadcastservice.ServiceUtil" />
整個流程就是:Activity 發送廣播 → 廣播接收方收到後啟動 Service 服務。從 LogCat 就能看到服務被成功喚醒的足跡。




10.5 AlarmManager:在指定時刻喚醒你的程式
本節導讀 本節主角是 AlarmManager(鬧鐘服務)。顧名思義,它常被拿來做手機鬧鐘 App;而官方文件的定義是:在指定時刻為你送出一個設定的 Intent。換句話
Android 佈局教學:TableLayout 表格佈局做出登入表單
TableLayout 把子元素分配到列與行之中。它由多個 TableRow 組成,每個 TableRow 定義一列,列內可以放 0 個或多個 Cell,每個 Cell
第34章 Android 拖動條 SeekBar:音量調節與三個關鍵事件
聽歌時左右拖動的播放進度、按側鍵調整的音量,背後都是同一個元件:SeekBar。它讓使用者用「滑動」這種最省力的手勢,連續地改寫一個數值,並即時看到結果。 一、版面:一
Android Studio 開發 Android App:安裝、建專案與運行
Android Studio 簡介Android Studio 是 Google 官方推薦的 Android 開發工具。本節將說明如何下載、安裝、建立專案並執行第一個 A