Android開發之Service與Activity資料互動(原始碼分享)

來源:互聯網
上載者:User

   Service想要與Activity進行資料互動,首先Activity先得綁定Service.bound service是service 的實現,它允許其他應用程式綁定到它並與之互動。要提供bound service,我們必須實現onBind()回調方法。這個方法返回一個內部對象定義的編程介面,Activity可以使用與Service進行互動。那麼具體該如何?呢,首先我們還是一樣先建立一個MyService繼承Service。然後如何設定:呢。(1)在你的Service,建立一個Binder執行個體,返回當前的Service執行個體以及一個Activity可以調用公用方法。(2)返回這個執行個體的Binder在onBind()回調方法。(3)在Activity裡建立ServiceConnection,在onServiceConnected()回調方法接受Binder,並得到伺服器的執行個體。講的比較囉嗦哦,我們還是看代碼來細細品味吧。

  Service的代碼

package com.example.f22_service02;import java.util.Random;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.os.Parcel;import android.os.RemoteException;import android.util.Log;public class HelloService extends Service {    private MyBinder binder=new MyBinder();public class MyBinder extends Binder{public HelloService getService(){return HelloService.this;  //返回Service執行個體,使主程式能調用該方法  }@Overrideprotected boolean onTransact(int code, Parcel data, Parcel reply,int flags) throws RemoteException {// TODO Auto-generated method stubLog.i("TAG", "------>"+data.readInt());Log.i("TAG", "------>"+data.readString());reply.writeInt(2);reply.writeString("Rose");return super.onTransact(code, data, reply, flags);}}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn binder; //回掉方法}public int getRandom(){return new Random().nextInt(100);}@Overridepublic void onCreate() {// TODO Auto-generated method stubLog.i("TAG", "------>Create");super.onCreate();}@Overridepublic boolean onUnbind(Intent intent) {// TODO Auto-generated method stubLog.i("TAG", "------>Unbind");return super.onUnbind(intent);}}

Activity的方法

package com.example.f22_service02;import com.example.f22_service02.HelloService.MyBinder;import android.os.Bundle;import android.os.IBinder;import android.os.Parcel;import android.os.RemoteException;import android.annotation.SuppressLint;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;@SuppressLint("Recycle")public class MainActivity extends Activity implements OnClickListener {private Button button, button2, button3;private MyBinder binder;private HelloService helloService;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button) this.findViewById(R.id.button1);button2 = (Button) this.findViewById(R.id.button2);button3 = (Button) this.findViewById(R.id.button3);button.setOnClickListener(this);button2.setOnClickListener(this);button3.setOnClickListener(this);}private ServiceConnection connection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stubLog.i("ACTIVITY", "---------〉失去綁定");}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubbinder = (MyBinder) service; // 綁定Service,並獲得Service執行個體,接下來就可以調用Service中的方法了helloService = binder.getService();Log.i("ACTIVITY", "---------〉綁定成功");}};@SuppressLint("Recycle")@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.button1:            //綁定ServiceIntent intent=new Intent(MainActivity.this,HelloService.class);bindService(intent, connection, Context.BIND_AUTO_CREATE);//第三個參數是一個標誌顯示選項綁定break;case R.id.button2://實現Activity與Service的資料互動//Parcel是一個容器,能包含訊息(資料和對象引用),可以通過一個IBinde發送            Parcel data=Parcel.obtain();            data.writeInt(helloService.getRandom());            data.writeString("jack");            Parcel reply=Parcel.obtain();        try {binder.transact(IBinder.LAST_CALL_TRANSACTION, data, reply, 0);} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();}        Log.i("ACTIVITY", "----Service回傳的值---->"+reply.readInt());        Log.i("ACTIVITY", "----Service回傳的值---->"+reply.readString());break;case R.id.button3:  //解除綁定             unbindService(connection);break;}}}


聯繫我們

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