2018-03-13 服务Service(一)-----开启服务及本地绑定

笔记如下


  • 服务介绍:下面试官方的说法

    3.png


  • 服务有两种形式:
    1.开启服务
    2.绑定服务


    3.png


编写服务的步骤:
1.继承一个service 类 , 那么就写了 一个服务
2.到 清单文件中进行配置
3.启动服务, 关闭服务

  • 开启服务
    配置文件中

        Intent intent  = new Intent();
        intent.setClass(this,TestService.class);
        //开启服务
        startService(intent);
        //关闭服务
        stopService(intent);
public class TestService extends Service {
      //实现抽象方法
}

在开启服务中是调用服务中的方法的

  • 绑定服务
    配置文件中

activity中


//绑定服务
 public void bindService(View v){
        Intent intent  = new Intent();
        intent.setClass(this,TestService.class);

        //绑定服务
        //conn:通讯的频道
        //BIND_AUTO_CREATE :绑定的时候就去创建服务
        //intent:找到了需要绑定的服务
        //new MyConnection():返回一个在目标服务中自定义方法的类(代理人)
         bindService(intent,conn,BIND_AUTO_CREATE);
}

    //IService是一个接口,里面声明了在服务中自定义的私有方法  
    IService agent ;

    private class MyConnection implements ServiceConnection{

        //当成功的绑定了服务,用于返回代理人
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            //获得了返回的代理人
            agent = (IService) service;

            System.out.println("绑定成功.....");
        }

        //当服务接触绑定的时候,会调用的方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
            //防止内存溢出
            agent = null;
            System.out.println("绑定失败.....");

        }
    }
   //调用服务中的自定义的方法
    public void call(View v){

        agent.callMethodServive("伯伯",250);

    }

Service中

public class TestService extends Service {


    //代理人
    //这里继承了Binder是IBinder的实现类
    private class MyAgent extends Binder implements IService {

        public void callMethodServive(String name , int money){

                methodInService(name,money);

        }
    }


    //当绑定了服务的时候,就会调用onBind方法,返回代理人
    @Override
    public IBinder onBind(Intent intent) {

        System.out.println("onbind执行了....服务被绑定了.....");
        return new MyAgent();
    }



    public void methodInService(String name , int money){

        Toast.makeText(this, "ok了.....", Toast.LENGTH_SHORT).show();
        System.out.println("服务中的方法被调用到了.....");

    }
}

IService 中

public interface IService {
     
    public void callMethodServive(String name , int money);
}

在绑定服务中就可以调用自己在服务中自定义的方法了

你可能感兴趣的:(2018-03-13 服务Service(一)-----开启服务及本地绑定)