Android之 服務(1)

來源:互聯網
上載者:User

標籤:size   ges   turn   gre   四大組件   ide   log   new   his   

1 簡介

服務是Android四大組件之一。不過與Activity不同的是,服務不會直接與使用者互動,而是摸摸地在後台運行。

有兩種方式來啟動系統服務。

一種是調用 Context.startService() 方法。另一種是調用 Context.bindService() 方法。

 

2 服務的生命週期

下面這張圖說明了服務的生命週期。當使用者調用Context.startService()或者Context.binService()時,系統會啟動服務。

如果服務沒有建立,那麼系統首先會調用Service類中的onCreate()方法,然後onStart()方法或者onBind()方法將會執行,開啟一個服務。

服務會一直默默地在後台進行,調用Context.stopService()或stopSelf()方法,服務中的onDestroy()會執行,銷毀服務。

當通過Context.bindService()開啟服務後,必須通過Context.unbindService()停止服務。

 

 

3 執行個體

3.1 通過Context.startService()啟動服務

首先建立一個類,繼承Service類。

public class MyService extends Service{        @Override    public IBinder onBind(Intent intent){        return null;    }        @Override    public void onCreate(){        super.onCreate();        Log.d("MyService","onCreate executed!");    }        @Override    public void onStart(Intent intent, int startId){        super.onStart();        Log.d("MyService","onStart executed!");    }        @Override    public void onDestroy(){        super.onDestroy();        Log.d("MyService","onDestroy executed!");    }    }

然後在活動中通過點擊按鈕,實現活動的啟動或停止。

 3.1 通過Context.bindService()啟動服務

 上面的方式,我們只能通過活動介面的按鈕來啟動和停止服務。如果服務想要跟活動更多的交流,就需要採用另外一種方式來開啟活動。

1、通過Context.bindService()啟動服務,我們同樣需要繼承Service類,重寫onBind()方法。

在onBind()方法中我們返回一個Binder對象。Binder類的API定義如下:

下面是具體代碼:

public class MyService extends Service {    private DownloadBinder mBinder = new DownloadBinder();        DownloadBinder extends Binder {        public void startDownload() {            Log.d("MyService", "startDownload executed");        }        public int getProgress() {            Log.d("MyService", "getProgress executed");            return 0;        }    }        @Override    public IBinder onBind(Intent intent) {        return mBinder;    }    ……}

 可以看到我們定義了一個內部類DownloadBinder繼承自Binder,在這個類中我們實現了兩個方法,用於啟動下載和擷取進度。

2、接下來就是在活動中通過Context.bindService()啟動服務,並且用上面的DownloadBinder中定義的方法,與服務隨時互動。

下面是具體代碼

public class MainActivity extends Activity implements OnClickListener {    private Button bindService;    private Button unbindService;        private MyService.DownloadBinder downloadBinder;    private ServiceConnection connection = new ServiceConnection() {            @Override        public void onServiceDisconnected(ComponentName name) {        }                @Override        public void onServiceConnected(ComponentName name, IBinder service) {            downloadBinder = (MyService.DownloadBinder) service;            downloadBinder.startDownload();            downloadBinder.getProgress();        }    };        @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ……        bindService = (Button) findViewById(R.id.bind_service);        unbindService = (Button) findViewById(R.id.unbind_service);        bindService.setOnClickListener(this);        unbindService.setOnClickListener(this);    }        @Override    public void onClick(View v) {        switch (v.getId()) {        case R.id.bind_service:            Intent bindIntent = new Intent(this, MyService.class);            bindService(bindIntent, connection, BIND_AUTO_CREATE); // 綁定服務            break;        case R.id.unbind_service:            unbindService(connection); // 解除綁定服務            break;        default:        break;        }    }}

 

Android之 服務(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.