Android開發之bindService()通訊

來源:互聯網
上載者:User

標籤:

Service啟動方式有兩種,startService(intent)和bindService(intent,conn,Context.BIND_AUTO_CREATE)

startService(intent),【onCreate()-  >onStartCommand()->startService()->onDestroy()】

該方法啟動service,會執行一個onStartCommand()的方法,所以一些操作就可以放在onStartCommand()中進行處理。

bindService(intent,conn,Context.BIND_AUTO_CREATE),【onCreate()->onBind()->onUnbind()->onDestroy()】

綁定啟動service,

使用該方法啟動service分為幾部

1.在Service中,重寫onBind()方法,返回一個iBinder對象。

1     @Override2     public IBinder onBind(Intent arg0) {3         // TODO Auto-generated method stub4         Log.d("learnservice", "綁定服務...");5         return new MyBinder();6     }

2.建立Service類BinderService,在BindService類裡建立內部類MyBinder,繼承Binder(Binder實現IBinder介面)。該類中實現一些與service通訊的方法,比如setData()方法。

1     public class MyBinder extends Binder{2         public void setData(String data){3             MyService.this.data=data;4         }5     }

3.在Activity裡,執行個體化ServiceConnection介面的實作類別,重寫onServiceConnected()和onServiceDisconnected()方法。

 1 ServiceConnection conn=new ServiceConnection() { 2          3         @Override 4         public void onServiceDisconnected(ComponentName name) { 5             // TODO Auto-generated method stub 6              7         } 8          9         @Override10         public void onServiceConnected(ComponentName name, IBinder service) {11             // TODO Auto-generated method stub12             binder=(MyBinder) service;   //該binder,需要在activity中聲明。13             Log.d("learnservice", "綁定服務conn...");14         }15     };

4.使用button的onClick()或者activity的onCreat()等觸發bindService()方法

1     @Override2     public void onClick(View v) {3         intent = new Intent(MainActivity.this,MyService.class);4         bindService(intent, conn, Context.BIND_AUTO_CREATE);
5 }

5.在activity中聲明service中的binder

1 private MyService.MyBinder binder;

6.同時把該binder放在serviceConnection的onServiceConnection()方法中

1 binder=(MyBinder) service;

這樣,就完成了Activity和Service通過bindService()方法綁定並通訊。

Android開發之bindService()通訊

聯繫我們

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