Activity绑定service,返回service实例。特别tabactivity绑定se...

   最近项目中用到Activity调用service的方法,并且Activity放在tabActivity中,当绑定的时候,会出现返回service会空的问题

public class MyService extends Service {
	//定义类继承Binder(IBinder的实现类), 其中
	//定义方法调用Service中的方法
	//返回MyService的实体类
	private class MyBinder extends Binder implements IBindService {

		@Override
		public void show(String name) {
			MyService.this.show(name);
		}

		@Override
		public MyService getService() {
			
			return MyService.this.getService();
		}

	}

	@Override
	public IBinder onBind(Intent intent) {
		System.out.println("onBind---------" );
		return new MyBinder(); // 返回IBinder
	}

	public void show(String name) {
		System.out.println("aaaa---------" + name);
		Toast.makeText(this,name, Toast.LENGTH_LONG).show();
	}

	
	@Override
	public void onDestroy() {
		System.out.println("onDestroy---------" );
		super.onDestroy();
	}
	public MyService getService() {
		return this;
	}

}

MyService中的接口,用于返回其实现类的对象-------IBindService

public interface IBindService {
	public void show(String name);
	public MyService getService();
}

 Activity实现类

public class MainActivity extends Activity {

	private Intent intent;
	private MyConn conn = new MyConn();
	//获取Binder实体类
	private IBindService iBindService;
	private Button button;
	//获取MyService实体类
	private MyService myService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		intent = new Intent(this, MyService.class);
		//startService(intent);
		bindService(intent, conn, BIND_AUTO_CREATE);
		//如果Activity放在tabActivity中的用以下的绑定
		//getApplicationContext().bindService(intent, conn, BIND_AUTO_CREATE);
		button = (Button) findViewById(R.id.button1);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// iBindService.show("chen");
				myService.show("chen");
//				stopService(intent);
				unbindService(conn);
				
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private class MyConn implements ServiceConnection {
		public void onServiceConnected(ComponentName name, IBinder service) {
			iBindService = (IBindService) service;
			//获取服务实体类
			myService = iBindService.getService();
		}

		public void onServiceDisconnected(ComponentName name) {
		}
	}

}

你可能感兴趣的:(Activity绑定service,返回service实例。特别tabactivity绑定se...)