绑定本地service并与之通信

来源:互联网 发布:coc治疗法术升级数据 编辑:程序博客网 时间:2024/05/01 20:56

如果Service和访问者之间需要进行调用或者数据交换,则应该则应该使用bindService()和unbindService()方法,启动.关闭service.
Context 的 boolean bindService (Intent service, ServiceConnection conn, int flags) :该方法的3个参数解释如下: 

  1. service: 该参数通过Intent 指定要启动的service.
  2. conn : 该参数是一个 ServiceConnection 对象,该对象用于监听访问者与service之间的连接情况.当访问者与service 之间连接成功时将调用该 ServiceConnection对象的 onServiceConnected(ComponentName name,IBinder service) 方法,当service所在的宿主进程由于异常终止或由于其他原因终止,导致该Service与访问者之间断开连接时回调该 ServiceConnection 对象的 onServiceDisconnected(ComponentName name)方法.
  3. flags : 指定绑定时是否自动创建Service(如果 service还未创建),该参数可指定为0(不自动创建),或 BIND_AUTO_CREATE (自动创建).

注意到 ServiceConnection对象的onServiceConnected方法中有一个 IBinder 对象,该对象即可实现被绑定service之间的通信.
当开发service类时,该 service类必须提供一个IBinder onBind(Intent intent),方法.在绑定本地service的情况下, onBind(Intent intent)方法所返回的 IBinder 对象将会传给ServiceConnection对象的 onServiceConnected(ComponentName name,IBinder service) 方法的service参数,这样访问者就可通过该 IBinder 对象与service进行通信.


实际上开发时通常采用继承Binder(IBinder 的实现类)的方式实现自己的IBinder 对象.


BindService绑定服务

package com.test.service.bindservice;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;/** * 示范 如何在Activity中绑定本地Service,并获取Service运行状态. */public class BindService extends Service {    private int count;    private boolean quit;    //定义 onBinder 方法所返回的对象    private MyBinder binder = new MyBinder();    public class MyBinder extends Binder    {        public  int getCount(){            //获取 service的运行状态            return count;        }    }    public BindService() {    }    @Override //必须实现的方法,绑定 该service时回调该方法    public IBinder onBind(Intent intent) {        Log.d("BindService", "onBind 绑定");        return binder;    }    @Override //创建 service时回调该方法    public void onCreate() {        super.onCreate();        Log.d("BindService", "onCreate");        //开启新线程 动态的修改 count状态值        new Thread(){            @Override            public void run() {                while (!quit){                    try {                        Thread.sleep(1000);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    count++;                }            }        }.start();    }    @Override //Service 被断开连接时回调该方法    public boolean onUnbind(Intent intent) {        Log.d("BindService", "onUnbind 解绑");        return true;    }    @Override //service 被关闭之前调用    public void onDestroy() {        super.onDestroy();        this.quit = true;        Log.d("BindService", "onDestroy 销毁");    }}

package com.test.service.bindservice;import android.app.Service;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.Toast;import com.test.service.R;public class BindServiceActivity extends AppCompatActivity {    Button btnBind, btnUnBind, btnStatus;    //保持所启动的service 的 IBinder对象    BindService.MyBinder mBinder;    //定义一个 ServiceConnection 对象    private ServiceConnection conn = new ServiceConnection() {        //当activity与 service连接成功时回调        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            Log.d("BindServiceActivity", "onServiceConnected 连接成功");            //获取 service中的  onBind方法返回的 MyBinder 对象            mBinder = (BindService.MyBinder) service;        }        //当activity与 service断开连接时回调        @Override        public void onServiceDisconnected(ComponentName name) {            Log.d("BindServiceActivity", "onServiceDisconnected 断开连接");        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_bind_service);        btnBind = (Button) findViewById(R.id.button4);        btnUnBind = (Button) findViewById(R.id.button5);        btnUnBind.setEnabled(false);        btnStatus = (Button) findViewById(R.id.button6);        //创建启动 vice的 Intent        final Intent intent = new Intent();        intent.setAction("com.test.service.BIND_SERVICE");        intent.setPackage(this.getPackageName());    //兼容Android 5.0        btnBind.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //绑定service                bindService(intent, conn, Service.BIND_AUTO_CREATE);                btnUnBind.setEnabled(true);            }        });        btnUnBind.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //解除绑定 service                unbindService(conn);            }        });        btnStatus.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //获取并显示 service 的count                Toast.makeText(BindServiceActivity.this, "service的count值: " + mBinder.getCount(), Toast.LENGTH_SHORT).show();            }        });    }}
0 0
原创粉丝点击