Android-服务Service(2)-bind绑定Service及两种生命周期

本文主要探讨了使用Context.bindService()方法绑定Service的过程,包括绑定、解绑服务的步骤以及ServiceConnection的相关回调。通过示例展示了Service的生命周期变化,指出startService后再绑定服务,解绑时不调用onDestroy(),而bindService创建的Service在解绑时会调用onDestroy(),强调了调用方式对Service生命周期的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上篇是第一种方法,这里主要是第二种Context.bindService()方法

1. 开发步骤

1. 绑定服务

Intent intent=new Intent(getBaseContext(),MyService.class); 
bindService(intent,connection, Context.BIND_AUTO_CREATE);

2. 解绑服务

unbindService(connection);

首先对于对于bindService()Method,

参数如下:
这里写图片描述

各个参数解释如下:

22222

  • 1.service:即通过intent指定的服务,与之前第一种方法一致

  • 2.conn:这是ServiceConnection的一个对象,其中有两个 函数,分别是onServiceConnected()和onServiceDisconnected(),用来监听访问者与Service之间的连接情况,当访问者与Service成功连接将回调onServiceConnected函数,当Service进程被crashed or killed(异常终止等)则回调onServiceDisconnected函数。

具体函数为:

    ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            method
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
//            method
        }
    };
  • 3.flag:即绑定时是否自动创建Service,如上参数图所示,0为不自动,BIND_AUTO_CREATE为自动创建

测试demo

MainActivity:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Intent intent=new Intent(getBaseContext(),MyService.class);
        Button btstart=(Button)findViewById(R.id.button1);
        Button btstop=(Button)findViewById(R.id.button2);
        Button btbind=(Button)findViewById(R.id.button3);
        Button btunbind=(Button)findViewById(R.id.button4);
        btstart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //启动服务
                startService(intent);
            }
        });
        btstop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //停止服务
                stopService(intent);
            }
        });
        btbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                bindService(intent,connection, Context.BIND_AUTO_CREATE);
            }
        });
        btunbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               unbindService(connection);
            }
        });

    }//onCreate
    ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            method
            System.out.println("onServiceConnected");
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
//            method
            System.out.println("onServiceDisconnected");
        }
    };
}

MyService:

public class MyService extends Service {
    public MyService() {
    }
  //绑定时调用
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        System.out.println("Service Binded");
//        throw new UnsupportedOperationException("Not yet implemented");
    return  new Binder();
    }
    // System.out 用于测试
    //创建时调用
    public void onCreate(){
        super.onCreate();
        System.out.println("Service Created");
        Toast.makeText(this,"Service Created",Toast.LENGTH_LONG).show();
    }
    //Service 启动时调用
    public int onStartCommand(Intent intent,int flags,int startID){
        System.out.println("Service Started");
        Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
        return  START_STICKY;
    }
    //关闭时调用
    public  void onDestroy(){
        super.onDestroy();
        System.out.println("Service Destroyed");
        Toast.makeText(this,"Service Destroyed",Toast.LENGTH_SHORT).show();
    }
    //解除绑定时调用
    public boolean onUnbind(Intent intent){
        System.out.println("Service Unbinded");
        return true;
    }
}

UI:

3333

测试:

4444444444

当按下绑定服务:

  • 首先自动创建服务(flag那设置的),回调onCreate()函数,
  • 之后绑定服务,回调onBind()函数
  • 最后回调ServiceConnection里面的onServiceConnection函数

之后按下解绑服务

  • 回调服务里面onUnbind()函数
  • 之后回调服务里面onDestroy()函数

2. 关于生命周期

在这里可以清晰看到,

startService后,再绑定服务。当解绑服务时候,Service并没有回调onDestroy()函数,
而绑定服务再解绑时,则会调用onDestroy()函数。

这是因为第一种情况,Service是由startService创建的,不是bindService。而第二种情况,则是bindService创建的Service。从这里发现,当bindService时,如果服务已经创建,那么解绑只是解除访问者与Service的绑定,而Service并不会终止。

这里关于生命周期,调用方法不同,周期也不同。

  • 调用startService周期:onCreate()-onStartCommand()-onDestroy()

  • 调用bindService周期:onCreate()-onBind()-Unbind()-onDestroy()

相关链接
Android-服务Service(1)-介绍及startService调用
Android-服务Service(2)-bind绑定Service及两种生命周期
Android-服务Service(3)-IntentService

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值