zoukankan      html  css  js  c++  java
  • Android之Service

    service :一直在后台运行!

    创建:

    1.创建一个继承service的子类!

    2.在Androidmainfest.xml中进行配置!

    启动方式(两种):

    1.Context.startService(new Intent());

        1) 通过该方法启动的service,service与访问者没有关联!即使访问者退出,service仍然可以运行!所以service不能与访问者进行数据交互

    停止方法:

        Context.stopService(new Intent());

    2.Context.bindService(new Intet(),Serviceconnection con,int flags);

        con :该对象中有两个方法需要重写

            onServiceConnected(ComponentName name,IBinder binder){

              // 该方法当访问者与Service绑定成功时回调!onBind()方法中返回的IBinder对象就是binder,这样就实现了service与访问者之间数据的交互!

            } 

            onServiceDisconnected(ComponentName name){

              // 该方法当程序异常,或者其他原因导致的访问者与service断开连接回调!   如果是调用unbindService()方法来停止服务 不回调!

            }

        2) 通过该方法启动的service,service与访问者进行绑定!如果绑定的访问者退出,停止service! 因此可以与访问者进行数据交互!

    停止方法:

        Context.unbindService(new Intent());

    生命周期:

    service的生命周期与之启动方式不同而略有不同!

    1.使用startService():onCreate()  -->  onStartconmmand() --> onDestroy()

    2.使用bindService() : onCreate()  -->  onBind()  --> onUnbind()  --> onDestroy()

    onCreate() :第一次创建service时~!执行”一“次!

    onStartconmmand(): 每次执行startService()时,回调!

    onDestroy(): 执行stopService()方法停止服务时,回调!

    onBind() :service子类必须实现的方法!该方法返回一个Ibinder对象!通过该方法程序可以与service进行通信!

    onUnbind() :当与该service绑定的客户端都断开连接时回调!

    IntentService :

    IntentService不是普通的Service,他是Service的子类,对Service进行了增强!

    Service不足:

    1.Service不会单独启用一个线程,他和他的应用在同一个线程中!

    2.Service 因为他不是在一条新线程中,所以不能执行耗时任务!

    IntentService 与之相反!

    继承IntentService的子类重写一个方法即可:

    onHandlerIntent(Intent intent){

    }

  • 相关阅读:
    设计模式(一)工厂模式Factory(创建型)
    Caused by: org.springframework.beans.factory.BeanCreationException
    从Delphi 7升级到Delphi XE
    system strategies of Resources Deadlock
    Service Manager流程,派BC_REPLY,唤醒FregServer流程,返回BR_TRANSACTION_COMPLETE,睡眠等待proc->wait
    Sqlserver2000联系Oracle11G数据库进行实时数据的同步
    火柴移动面试题
    Eclipse4.4设备egit插件提交本地项目代码到远程仓库
    V离MWare至Openstack至FDIO
    【BZOJ1791】【IOI2008】【基环树】island(status第一速度)
  • 原文地址:https://www.cnblogs.com/shiguotao-com/p/5197008.html
Copyright © 2011-2022 走看看