zoukankan      html  css  js  c++  java
  • 绑定本地Service并与之通信-----之一

    import android.app.Service;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;

    public class BindService extends Service{
      private int count;
      private boolean quit;
      //定义onBinder方法所返回的对象
      private MyBinder binder = new MyBinder();
      //通过继承Binder来实现IBinder类
      public class MyBinder extends Binder{
        public int getCount(){
          //获取Service的运行状态:count
          return count;
        }
      }

      //必须实现的方法
      @Override
      public IBinder onBind(Intent intent) {
        System.out.println("Service is Binded");
        //返回IBinder对象
        return binder;
      }

      //Service被创建时回调该方法
      @Override
      public void onCreate() {
        super.onCreate();
        System.out.println("Service is Created");
        //启动一条线程、动态地修改count状态值
        new Thread(){
          public void run() {
            while(!quit){
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              count++;
            }
          }
        }.start();
      }
      //Service被断开连接时回调该方法
      @Override
      public boolean onUnbind(Intent intent) {
        System.out.println("Service is Unbinded");
        return true;
      }

      //Service被关闭之前回调
      @Override
      public void onDestroy() {
        super.onDestroy();
        this.quit = true;
        System.out.println("Service is Destroyed");
      }

    }

  • 相关阅读:
    希望多年以后的自己不再如此迷茫
    【转载】撒旦(Satan 4.2)勒索病毒最新变种加解密分析
    java单例模式
    关于double/float 两种基本类型精度丢失的总结
    关于ecplise中一些很实用的技巧
    安装SQL Server和卸载SQL Server步骤
    我进入部门的第一周
    mysql数据库在Linux和windows下免安装实现以及框架开发碰到的问题
    jenkins发布docker到mesos
    u盘作为git仓库,完成不同地方的代码同步
  • 原文地址:https://www.cnblogs.com/jiww/p/5602640.html
Copyright © 2011-2022 走看看