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

    @、Context.startService(Intent)

    lifecycle callback:

    1、onCreate(...)

    2、onStartCommande(Intent, int, int)

    3、onDestroy()

    stop service:

    1、Service.stopSelf() / stopSelf(int)

    2、Context.stopService(Intent)

    @、Context.bindService

    lifecycle callback:

    1、onBind(...)

    2、onUnbind()

    stop service:

    1、Context.unbindService() (当所有客户端都执行完此操作,服务会自动关闭,除了调用Service.startForeground()的情况。)

    @、保持Service不被终止

    在服务里调用startForeground(),这种情况要正确调用stopForeground()来终止服务,否则服务一直运行。

    @、与Activity通信:

    1、使用sendBroadcast(Intent)。

    2、在Service中添加会调接口及接口实例及实例的set方法,而Activity实现此接口。这种方法可结合Locally Bound Service模式进行使用,这样可以在Activity中直接调用Service的方法。

    @、IntentService

    1、HandlerThread,Handler,Message模式。

    2、继承IntentService只需要实现onHandleIntent(Intent)方法。

    3、以上两点决定了,使用IntentService不用再创建线程,而onHandleIntent每次只能处理一个Intent,因此如果存在耗时长的Intent,则此IntentService的其他Intent就有可能被阻塞。

    @、自定义Service实现并行服务

    1、在自定义Service中添加ExecutorService实例成员,通过它的excute(Runnable)来执行任务。通过startForeground(),保持服务后台运行,通过计数成员变量记录当前任务数量,根据当前任务数量决定是否调用stopForeground()来终止服务。

    注:关于Service的示例见Android Programming: Pushing the Limits -- Chapter 6: Services and Background Tasks

  • 相关阅读:
    解析Javascript事件冒泡机制
    LeetCode——Flatten Binary Tree to Linked List
    流动python
    HDU2586
    Cannot find ActionMappings or ActionFormBeans collection
    reactor设计模式
    简单的Ajax应用实例
    CString——Left、Right、Find、ReverseFind
    MATLAB新手教程
    八大排序算法总结
  • 原文地址:https://www.cnblogs.com/yarightok/p/5790492.html
Copyright © 2011-2022 走看看