Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android學習_Service

Android學習_Service

編輯:關於Android編程

description: 從官方的文檔就可以看出Service應用程序的模塊之一,當應用程序需要去做一些需要長時間運行的操作(後台處理一些耗時的邏輯),並且不需要與用戶進行交互,這個時候就可以用Service來在後台實現。

最近又開始重新折騰起Android開發,之前趕項目的時候簡單地做過一個Android應用,現在的話又要重新學起了…不廢話了。

概述

public abstract class

Service

extends ContextWrapper

implements ComponentCallbacks2

A Service is an application component representing either an application’s desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding declaration in its package’s AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

從官方的文檔就可以看出Service應用程序的模塊之一,當應用程序需要去做一些需要長時間運行的操作(後台處理一些耗時的邏輯),並且不需要與用戶進行交互,這個時候就可以用Service來在後台實現。

那麼總結一下Service的特點

後台運行,通常是應用的一個功能模塊; 通常是長時間運行的邏輯操作,即使程序退出的情況下,依然可以讓Service在後台保持運行狀態; 不需要和用戶進行交互; 在整個應用程序中都是通用的; 運行在主線程,因此不能用來做耗時的請求或操作(可以在服務裡新開一個線程)。

Service的分類

通常把Service分為兩類:

本地服務:Local Service用於應用程序內部,通過調用Context.startService()啟動,調用Context.stopService()結束。在內部可以調用Service.stopSelf()來自己停止。無論調用了多少次startService(),只需要調用一次stopService()來停止。 遠程服務:Remote Service用於系統內部的應用程序之間,可以定義接口以便進行其他的操作。客戶端建立到服務對象的連接,並通過那個連接來調用服務。調用Context.bindService()方法建立連接並啟動,調用Context.unbindService()關閉連接。

Service的生命周期

Service只繼承了onCreate()onStartCommand()onDestroy()三個方法,第一次啟動Service的時候,先後調用了onCreate()、onStartCommand()這兩個方法,當停止Service時,則執行onDestory()方法,而當我們的Service已經啟動的時候,再次啟動就直接執行onStartCommand()方法(去手機的應用程序管理器可以查看自己的Service是否處於運行狀態)。

Service的使用

通常的用法就是用Intent啟動Service,重寫父類的onCreate()、onStartCommand()和onDestroy()方法。

Service與Activity的通信

可以在Activity中啟動一個service,那麼如何讓兩者之間建立通信關系呢,這裡寫一部分偽代碼。

public class MyService extends Service {

    public static final String M_TAG = MyService;

    private MyBinder m_binder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(M_TAG, onCreate() executed);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i(M_TAG, onStartCommand() executed);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.i(M_TAG, onDestroy() executed);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return m_binder;
    }

    class MyBinder extends Binder {

        public void MyMethod() {

            Log.i(M_TAG, Start MyMethod());
            // ...
        }
    }
}

啟動一個Service實際上是開啟一個新的進程,那麼Service和Activity之間的通信實際上就是不同進程間的通信問題(暫時不多敘述)。上面的代碼用到了IBinder,這是個什麼樣的東西呢?

public interface

IBinder

Base interface for a remotable object, the core part of a lightweight remote procedure call mechanism designed for high performance when performing in-process and cross-process calls. This interface describes the abstract protocol for interacting with a remotable object. Do not implement this interface directly, instead extend from Binder.

IBinder是遠程對象的一個基本接口,一個為進程和跨進程調用服務的輕量級的遠程調用機制的核心部分,該接口描述了一個抽象的協議。上述的偽代碼中實現了一個自定義的MyBinder方法,在其中加入了自己的MyMethod方法。

接下來,修改啟動MyService的MainActivity:

public class MainActivity extends Activity {

    // ...

    private MyService.MyBinder m_binder;

    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            m_binder = (MyService.MyBinder)service;
            m_binder.MyMethod();
        }

        @Override
        public void onServiceDisconnected(ComponentName name, IBinder service) {
            // ..
        }
    };

    // ...
}

public interface

ServiceConnection

Interface for monitoring the state of an application service. Like many callbacks from the system, the methods on this class are called from the main thread of your process.

這裡創建了一個匿名的類ServiceConnection,重寫了onServiceConnected和onServiceDisconnection方法,這兩個方法會在Activity與Service建立和解除connection的時候調用。然後通過IBinder接口,Activity就可以調用Service內部的方法。

當然兩者的綁定還需要調用bindService(Intent, ServiceConnection, int)接口,這裡第三個參數int是一個標志位。

BIND_ALLOW_OOM_MANAGEMENT:allow the process hosting the bound service to go through its normal memory management. BIND_AUTO_CREATE:automatically create the service as long as the binding exists. BIND_DEBUG_UNBIND: include debugging help for mismatched calls to unbind. BIND_IMPORTANT:this service is very important to the client, so should be brought to the foreground process level when the client is. BIND_NOT_FOREGROUND:don’t allow this binding to raise the target service’s process to the foreground scheduling priority. BIND_WAIVE_PRIORITY:don’t impact the scheduling or memory management priority of the target service’s hosting process.

解除兩者之間的connection只需要調用unbindService(connection)接口即可。

當然Service不僅可以和建立它的Activity之間建立connection,和應用程序內的其他Activity也是可以建立connection的,並且可以獲取相同的extends IBinder的實例。

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved