首页 > 代码库 > client怎样调用IBinder接口对象

client怎样调用IBinder接口对象

代码:

	public void funclick(View view){
		Intent _intent = new Intent(MainActivity.this,MyService.class);
		bindService(_intent, conn, BIND_AUTO_CREATE);
	}
	
	private ServiceConnection conn = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			String mynameStr = ((MyBinder)service).helloWorld("bitch");
			Log.e("mynameStr", mynameStr+"~");
		}
	};

对于这种一个service.有什么不同呢。服务端的代码能够參照我上篇博文,通过打印log发现。onStart或者onstartCommand并没有被调用哦。

到此,我们仍然不会满足,由于我们仅仅是调用了MyBinder中的方法,并没有调用Myservice方法嘛。所以。我们要添加一个返回MyserVice的方法:

package com.example.mydownload;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

//实现接口中的方法
	 
public class MyService extends Service {
	//接口对象
	IBinder mybBinder = new MyBinder();
	
	class MyBinder extends Binder{
		<span style="color:#ff0000;">public MyService getMyService(){
			return MyService.this;
		}</span>
	public String helloWorld(String name){
			return name;
		}
	}
	
	@Override
	public void onCreate() {
		Log.e("log", "onCreate");
		super.onCreate();
	}
Log.e("log", "hello,bitch!");


	@Override
	public void onDestroy() {
		Log.e("log", "onDestroy");
		super.onDestroy();
	}


	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.e("log", "onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}

	
	@Override
	public IBinder onBind(Intent arg0) {
		return mybBinder;
	}

}



然后改动client代码:

@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			((MyBinder)service).getMyService().helloService();
		}


client怎样调用IBinder接口对象