• 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

  • 相关阅读:
    vmware虚拟机迁移系统到其它磁盘(xjl456852原创)
    值得思考的
    OS X系统特有文件目录说明
    计算机组成原理语言层级
    PC启动过程详解
    对大学计算机培养方案路线回顾
    Django学习笔记(二)App创建之Model
    Django学习笔记 (一) 开发环境配置
    HTML的发展历史
    如何设置MySql Server远程访问(Debian Linux)
  • 原文地址:https://www.cnblogs.com/NuoChong/p/11990152.html
Copyright © 2020-2023  润新知