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

第84章:Service 之二——與 Activity 綁定的用法(從零開始學 Android)

編輯:Android 技術基礎

Android 裡的 Service(服務)到底是什麼樣的存在?如果你熟悉 Windows 系統的服務,不妨把它們想成一回事;若不太了解也無妨,你只要把 Service 當成一個「沒有界面的 Activity」來理解就可以了。

Service 運行在後台,看不見、也沒有畫面。你可以啟動一個服務來播放音樂、記錄地理位置的變化,或是讓它持續運行、不斷監聽來電與短信等事件。

既然把它當成無界面的 Activity,那麼它同樣運行在主線程上,因此不適合用來做耗時的請求或運算。真有耗時操作時,仍然得在服務裡另開一條線程,把重活交給它去做。

服務的兩種型態

(1)本地服務 Local Service:用於應用程式內部。可用 Context.startService() 啟動、Context.stopService() 結束;在內部也能用 Service.stopSelf() 或 Service.stopSelfResult() 自行停止。無論呼叫多少次 startService(),只需呼叫一次 stopService() 即可停止。

(2)遠程服務 Remote Service:用於 Android 系統內部的應用程式之間。你可以定義並暴露出介面,供其他應用操作。客戶端透過 Context.bindService() 建立連接並啟動,用 Context.unbindService() 關閉連接。多個客戶端可以綁定同一個服務;若服務尚未載入,bindService() 會先把它載入。這類服務可被其他應用重複使用,例如定義一個天氣預報服務,讓其他 App 直接呼叫即可。

Service 生命週期

Service 的生命週期比 Activity 單純一些,主要圍繞 onCreate()、onStart()、onDestroy() 三個方法。第一次啟動服務時,會依序呼叫 onCreate() 與 onStart();停止服務時則執行 onDestroy()。若服務已啟動,再次啟動時不會重跑 onCreate(),而是直接執行 onStart()。服務可以透過 stopSelf() 或 stopSelfResult() 自我了結;而只要呼叫一次 stopService(),無論之前啟動過多少次,都能把服務停下來。

本章案例示範 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/startservice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="啟動Service" />

    <Button
        android:id="@+id/stopservice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止Service" />

    <Button
        android:id="@+id/bindservice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="綁定Service" />

    <Button
        android:id="@+id/unbindservice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="解除Service" />

</LinearLayout>

二、程式檔

1. ServiceUtil.java

打開 src/com.genwoxue.service/ServiceUtil.java,這裡透過自訂的 Binder 回傳介面描述,並觀察綁定相關的回呼:

package com.genwoxue.servicebind;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class ServiceUtil extends Service {

    private String TAG="Service:";

    private IBinder binder=new Binder(){
        @Override
        public String getInterfaceDescriptor(){
            return "Service class";
        }
    };


    @Override
    public IBinder onBind(Intent intent){
        Log.i(TAG, "服務開始綁定:onBind() Intent="+intent);
        return binder;
    }

    @Override
    public void onRebind(Intent intent){
        Log.i(TAG, "服務重新綁定:onRebind() Intent="+intent);
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent){
        Log.i(TAG, "服務解除綁定:onUnbind() Intent="+intent);
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate(){
        Log.i(TAG, "服務開始創建:onCreate()!");
    }

    @Override
    public void onDestroy(){
        Log.i(TAG, "服務銷毀:onDestroy()!");
    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        Log.i(TAG, "服務啟動:onStart()=>Intent"+intent+",startID="+startId);
        return Service.START_CONTINUATION_MASK;
    }

}

2. MainActivity.java

打開 src/com.genwoxue.service/MainActivity.java,透過 ServiceConnection 觀察綁定與解除的時機:

package com.genwoxue.servicebind;


import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;

import android.content.ComponentName;

public class MainActivity extends Activity {


    private Button btnStart=null;
    private Button btnStop=null;
    private Button btnBind=null;
    private Button btnUnBind=null;

    private String TAG="Service:";

    private ServiceConnection serviceConn=new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName name,IBinder service){
            try{
                Log.i(TAG,"服務連接成功:service="+service.getInterfaceDescriptor());
            }catch(RemoteException e){
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name){
            Log.i(TAG,"服務斷開連接!");
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnStart=(Button)super.findViewById(R.id.startservice);
        btnStop=(Button)super.findViewById(R.id.stopservice);
        btnBind=(Button)super.findViewById(R.id.bindservice);
        btnUnBind=(Button)super.findViewById(R.id.unbindservice);

        btnStart.setOnClickListener(new OnClickListener(){
            public void onClick(View v)
            {
                Intent intent=new Intent(MainActivity.this,ServiceUtil.class);
                MainActivity.this.startService(intent);
            }
        });

        btnStop.setOnClickListener(new OnClickListener(){
            public void onClick(View v)
            {
                Intent intent=new Intent(MainActivity.this,ServiceUtil.class);
                MainActivity.this.stopService(intent);
            }
        });


        btnBind.setOnClickListener(new OnClickListener(){
            public void onClick(View v)
            {
                Intent service=new Intent(MainActivity.this,ServiceUtil.class);
                MainActivity.this.bindService(service,MainActivity.this.serviceConn,Context.BIND_AUTO_CREATE);
            }
        });

        btnUnBind.setOnClickListener(new OnClickListener(){
            public void onClick(View v)
            {
                MainActivity.this.unbindService(MainActivity.this.serviceConn);
            }
        });

    }

}

三、設定檔

打開 AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.genwoxue.servicebind"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        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.servicebind.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.servicebind.ServiceUtil" />
    </application>

</manifest>

要啟用服務,同樣得在 AndroidManifest.xml 註冊它:

<service android:name="com.genwoxue.servicebind.ServiceUtil" />

四、運行結果

1. 第一步,在 LogCat 中建立名為「Service」的過濾器,方便觀察服務相關的日誌。

2. 運行 Service App,依序按下啟動、綁定、解除、停止等按鈕,觀察日誌中 onCreate()、onBind()、onUnbind()、onDestroy() 的觸發順序,就能清楚掌握綁定式服務的生命週期。

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