Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

第92章:用廣播 Broadcast 點亮 Service(從零開始學 Android)

編輯:Android 技術基礎

在 Android 的世界裡,Service(服務)扮演著舉足輕重的角色。它沒有畫面,卻能在背後默默為我們播放音樂、追蹤定位、監聽來電與短信。既然 Service 如此重要,那麼如何把它「喚醒」就成了一門學問。

前面我們已經學會用 Activity 直接啟動服務,你可能會問:既然 Activity 就能搞定,為什麼還要繞道廣播?別急,等到後續我們動手做「來電監聽」「短信監聽」時,你就會明白廣播這種「一喊百應」的解耦方式有多香。本章,我們就來動手實作:如何透過一則廣播,把 Service 啟動起來。

一、設計界面

1. 佈局檔

打開 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>

二、程式檔

1. 建立 ServiceUtil.java

新增 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()");
    }

}

2. 建立 BroadcastReceiverUtil.java

接著新增 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));
        }

    }
}

3. 編輯 MainActivity.java

最後打開 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 就能看到服務被成功喚醒的足跡。

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