android 將Service綁定到Activity

來源:互聯網
上載者:User

標籤:android   java   os   io   cti   ar   new   amp   

Service可以和Activity綁定,後者會維持對Service執行個體的引用,此引用允許你像對待其他執行個體化的那樣,對正在啟動並執行Service進行方法調用。

允許Service和Activity綁定,這樣能夠獲得更加詳細的介面。要讓一個Service支援綁定,需要實現onBind方法,並返回被綁定Service的當前執行個體。

package com.example.androidtest.service;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;public class MyService extends Service {private final IBinder binder = new MyBinder();@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn  binder;}public class MyBinder extends Binder{MyService getService(){return MyService.this;}}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();}}

Service和其他組件之間的串連表示為一個ServiceConnection.

要想將一個Service和其他組件進行綁定,需要實現一個新的ServiceConnection,建立一個串連之後,就可以通過重寫onServiceConnected和onServiceDisconnectd方法來獲得對service的引用。程式:

package com.example.androidtest;import com.example.androidtest.service.MyService;import android.os.Bundle;import android.os.IBinder;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.view.Menu;public class MainActivity extends Activity {private MyService myService;//service和activity之間的串連private ServiceConnection mConnection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName arg0) {// TODO Auto-generated method stubmyService = null;}@Overridepublic void onServiceConnected(ComponentName className, IBinder service) {//當建立串連時調用myService = ((MyService.MyBinder)service).getService();}};public void toBind(){//綁定一個serviceIntent bindIntent = new Intent(MainActivity.this,MyService.class);bindService(bindIntent, mConnection, BIND_AUTO_CREATE);}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.