让Activity和Service建立联系(单向通讯)

1. 我们建立一个自己的Service, 继承于Service类

public class ContentParseService extends Service



2. 由于Service和Activity通讯是通过Binder来进行, 所以需要在Service内部(或者另外一个文件? 为了让这个Binder使用ContentParseService的相关变量/方法, 还是将它放在Service内部吧)来实现一个自己的Binder, 当然也是继承于Binder.
public class CommunicateBinder extends Binder



3. 如何使用Binder呢? 可以在ContentParseService内部声明一个CommunicateBinder变量:
private CommunicateBinder mCommBinder = new CommunicateBinder();



4. 然后你就可以在CommunicateBinder内实现提供给Activity的公共方法, 比如:
    
public class CommunicateBinder extends Binder
		{
			public void getHomePageContent()
			{
				// do something here
			}
		}



5. 那么Activity端怎么使用呢? Activity和Service通讯是通过一个ServiceConnection的类来进行的, 那么我们可以这样来定义:
private ContentParseService mContParseBinder = null;
	private ServiceConnection conn = new ServiceConnection()
	{
		@Override
        public void onServiceConnected(ComponentName name, IBinder service) {
			mContParseBinder = (ContentParseService.CommunicateBinder)service;
			// do something here, 
			//建立了联系后, 就可以使用ContentParseService的方法了, 如getHomePageContent(), like this:
			mContParseBinder.getHomePageContent();
		}
		
		@Override
        public void onServiceDisconnected(ComponentName name) {
            // do something here
        }
	};



6. 光定义了ServiceConnection变量还不行, 还需要一些额外的动作让Service和Activity建立关系, 这里我们就使用Intent来实现, 在Activity中:
/* 启动解析服务 */
        Intent contentParseService = new Intent(this, ContentParseService.class);	//ContentParseService.class这个是前面我们定义ContentParseService类的类名 + class
        this.startService(contentParseService);	//Context类型中可以使用this, Activity属于Context的一种


		//或者使用
        Intent bindIntent = new Intent(this, ContentParseService.class);
        bindService(bindIntent, conn, BIND_AUTO_CREATE);	//conn是前面定义的变量, 也就是ServiceConnection



关于startService和bindService的区别, 烦请去Google了, Baidu也是可以, 虽然不太准确

7. 基本上, Activity和Service就这样建立了联系, 注意, 我们这里建立的Service和Activity属于同一个UI线程, 不要在Service中做耗时的操作, 如果要, 那么请在Service中建立线程来进行, 或者使用远程Service(使用AIDL, 这样Service就和Activity属于两个进程了, 但是没有必要这样做吧, 重新启动一个进程, 系统又增加了负担).


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值