Service的运用与activity的通信

作者: 缘狄 | 来源:发表于2016-10-24 14:02 被阅读86次

    今天突然想起有关于Service这个东西的存在,然后去网上找资料来学习,之前呢,只知道这是一个服务,这个服务是什么,能干什么,分为什么和什么,我是都不清除的,今天趁早还有点空闲时间,就去搜寻资料来学习学习,我找到的是郭霖大神的博客,网址是:Service完全解析,不得不说郭霖对Android的理解很高,我只能在他的脚底仰望,经过半天学习,也对service的运用也有了一些理解,就来分享一下,与其说是理解,不如说是怕我自己以后忘了,写到备忘录。

    首先Service是Android四大组件之一,这是众所周知的,他的功能也是十分强大的,至于强大到哪里,我也不甚清楚,他分为前台服务和后台服务,后台服务就是用户看不见的,但是一直在默默做事的,前台和后台的区别就是优先级稍微高一些,不会那么容易被杀死,下面则开始使用。

    创建一个类,继续Service,复写onBind()方法,这个类的作用在下面会讲:

    /**

    * Created by admin on 2016/10/21.

    */

    publicclassMyServiceextendsService {

    @Override

    publicvoidonCreate() {

        super.onCreate();

    }

    @Override

    publicintonStartCommand(Intent intent,intflags,intstartId) {

    returnsuper.onStartCommand(intent, flags, startId);

    }

    @Override

    publicvoidonDestroy() {

    super.onDestroy();

    }

    @Nullable

    @Override

    publicIBinder onBind(Intent intent) {

    returnnull;

    }

    然后是在Actiivty中注册服务:

    Intent intent =newIntent(MainActivity.this,MyService.class);startService(intent);

    有注册当然也有取消:

    Intent intent =newIntent(MainActivity.this,MyService.class);stopService(intent);

    使用是很简单的,当然不要忘记在清单文件中注册:

    <serivce>android:name=".MyService"/>

    ,这便是服务的使用了,很简单的一个东西,接下来便是与activity 的通讯了,这里就需要用到上面复写的方法onBind(),首先写一个内部类,基础Binder:

    classMyBinderextendsBinder {public voidDownload() {

    }

    }

    然后在MyServic中:

    privateMyBinder binder =newMyBinder();

    ,

    @Nullable

    @Override

    publicIBinder onBind(Intent intent) {

    returnbinder;

    }

    即可,接下来则是activity中的|:

    privateMyService.MyBinder myBinder;

    privateServiceConnection connection =newServiceConnection() {

    @Override

    publicvoidonServiceConnected(ComponentName componentName, IBinder iBinder) {

    myBinder = (MyService.MyBinder) iBinder;

    myBinder.Download();

    }

    @Override

    publicvoidonServiceDisconnected(ComponentName componentName) {

    }

    };

    然后是绑定:

        Intent intent =newIntent(MainActivity.this, MyService.class);

    bindService(intent,connection,BIND_AUTO_CREATE);

    解绑则是:

    unbindService(connection);

    ,如果你使用

    ServiceConnection ,记得要在ondestry中解绑,要不然报异常

    相关文章

      网友评论

        本文标题: Service的运用与activity的通信

        本文链接:https://www.haomeiwen.com/subject/fbrluttx.html