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属于两个进程了, 但是没有必要这样做吧, 重新启动一个进程, 系统又增加了负担).