zoukankan      html  css  js  c++  java
  • 7、认识 Android Service

    1、使用Service
    什么是service,在很多时候我们的程序不需要可以与用户交互的界面,他只需要在后台运行做一些事务的处理,比如socket长连
    接,这就要使用service

    创建service:
    右边菜单new Service
    如何启动service
    startService(new Intent(MainActivity.this, 类.class/*MyService.class*/));
    停止服务
    stopService(new Intent(MainActivity.this, 类.class/*MyService.class*/));


    public int onStartCommand(Intent intent, int flags, int startId)
    执行完startservice调用


    2、绑定Service

    bindService(intent,this, Context.BIND_AUTO_CREATE);

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
    //服务被绑定成功后执行
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
    //服务所在的进程奔溃的时候或者被杀掉的时候调用
    }


    @Override
    public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    // throw new UnsupportedOperationException("Not yet implemented");
    return new Binder();
    }
    3、Service的生命周期

    public void onCreate()
    public void onDestroy()
    如果,同时启动服务并且绑定服务,那么必须同时停止服务,解除绑定,服务才可以停掉
    如果说你的activity 与某个service进行绑定的话,那么在你退出activity的时候,服务会取消绑定(不求同世生但求同时死)
    重复去执行启动服务的操作我们会发现onStartCommand会执行很多次,oncreate只会执行一次onStartCommand,只要执行startService(intent); 在内部就会执行onStartCommand

  • 相关阅读:
    P3916 图的遍历 dfs
    P4568 [JLOI2011]飞行路线 分层图最短路
    P1948 [USACO08JAN]电话线Telephone Lines spfa 二分答案
    P1849 [USACO12MAR]拖拉机Tractor bfs
    P1730 最小密度路径 floyed
    P1661 扩散 二分答案 并查集
    使用unittest和Django搭配写一个接口测试平台
    AJAX解决跨域的几种方式
    Django
    基于pytest框架自动化测试脚本的编写
  • 原文地址:https://www.cnblogs.com/NuoChong/p/11990152.html
Copyright © 2011-2022 走看看