绑定本地Service并与之通信

来源:互联网 发布:步步高v206b软件现在 编辑:程序博客网 时间:2024/05/01 14:15

自己总结了一下绑定本地Service并与之通信步骤:

自己总结的Service与activity间通信的步骤(一些地方解释的不正确,仅参考):在Service类中1、创建myService类继承自Service2、通过继承Binder(IBinder的实现类)的方式来实现自己的IBinder对象3、在onBinder(Intent intent)方法中返回IBinder对象4、重写myService中的onCreate()方法   重写myService中的onUnbind()方法<如果想解绑之后可以再次绑定,此函数需要return true>       重写myService中的onRebind()方法<解绑之后再次绑定调用的函数>   重写myService中的onDestroy()方法在Activity中1、声明Binder对象用于接收该Activity与Service连接成功时   获取Service的onBind()方法所返回的binder对象2、new一个内名内部类来实现ServiceConnection这个接口并重写其中的两个方法:   ServiceConnected()ServiceDisConnected()方法3、为按钮绑定监听器,实现绑定解绑等事件。mainifest中注册Service

java代码:

mainactivity:

package com.example.zhang.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;public class MainActivity extends AppCompatActivity {    Button mStart, mStop, mBindService, mUnBindService, mGetCount;    /**     * 这里详细解释一下startService、stopService、还有bindService     * startService、stopService启动或者关闭service,通常Service与访问者之间没有什么太大的关联,     * 因此Service与访问者之间也无法进行通信交换数据     *     * 当开发Service类时,该Service类必须提供一个IBinder onBind(Intent intent)方法,     * 当Activity绑定了本地Service时,IBinder onBind(Intent intent)方法所返回的IBinder对象会传给     * ServiceConnection对象里面的onServiceConnected(ComponentName, IBinder service)方法的service参数,     * 这样访问者就可以通过该IBinder对象与Service通信了     *     * 而bindService()可以用来绑定本地Service并与之通信     * 完整方法:bindService(Intent service, ServiceConnection conn, int flags)     * 这里详细解释一下第二个参数(个人见解<不一定对>)     * 第二个参数是一个ServiceConnection对象,该对象用于监听访问者与Service之间的连接情况     * 当访问者与Service之间连接成功时将回调该ServiceConnection对象的onServiceConnected(ComponentName,IBinder Service)方法;     * 当Service所在的宿主进程由于异常或者其他原因终止,导致该Service与访问者之间断开连接时,     * 回调该ServiceConnection对象的onServiceDisconnected(ComponentName name)方法。     * 通俗点讲就是:     * service与activity进行通讯的要使用bindService(Intent service, ServiceConnection conn, int flags)方法     * 而这个方法中包含一个ServiceConnection conn参数,所以要在activity中声明这个类,并且重写他的两个方法     * onServiceConnected()和onServiceDisconnected()方法,这两个方法分别在连接到Service和断开与Service连接时回调,     */    //声明对象的引用用来保存ServiceConnected获取到的binder对象    FirstService.MyBinder binder = null;    private ServiceConnection coon  = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            binder = (FirstService.MyBinder) service;            Log.i("MainActivity", "已连接");        }        @Override        public void onServiceDisconnected(ComponentName name) {            Log.i("MainActivity", "断开连接");        }    };    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();        final Intent intent = new Intent(MainActivity.this, FirstService.class);        setClickListener(intent);    }    private void setClickListener(final Intent intent) {        mBindServiceClick(intent);        mBindServiceClick();        mStartServiceClick(intent);        mStopSeviceClick(intent);        mGetCount.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //这里先做一个判断,如果还没有创建Service(此时binder为null)时,输出提示信息                //因为如果没有线创建Service就点击获取Count程序会出现异常终止                if(binder != null)                Toast.makeText(MainActivity.this, "获得的Count值为:" + binder.getCount(), Toast.LENGTH_SHORT).show();                else {                    Log.i("main", "请先创建Service");                }            }        });    }    private void mStopSeviceClick(final Intent intent) {        mStop.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                stopService(intent);            }        });    }    private void mStartServiceClick(final Intent intent) {        mStart.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                startService(intent);            }        });    }    private void mBindServiceClick() {        mUnBindService.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //这里先做一个判断,如果还没有创建Service(此时binder为null)时,输出提示信息                //因为如果没有线创建Service就点击解绑,程序会出现异常终止                if(binder != null) {                    unbindService(coon);                }                else {                    Log.i("main", "请先创建Service");                }            }        });    }    private void mBindServiceClick(final Intent intent) {        mBindService.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                bindService(intent, coon, BIND_AUTO_CREATE);            }        });    }    private void initView() {        mStart = (Button) findViewById(R.id.btnStart);        mStop = (Button) findViewById(R.id.btnStop);        mBindService = (Button) findViewById(R.id.btnBindService);        mUnBindService = (Button) findViewById(R.id.btnUnBindService);        mGetCount = (Button) findViewById(R.id.btnGetCount);    }}

firstService:

package com.example.zhang.service;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.support.annotation.Nullable;import android.util.Log;/** * Created by zhang on 2016/1/9. * 这里详细解释一下startService、stopService、还有bindService * startService、stopService启动或者关闭service,通常Service与访问者之间没有什么太大的关联, * 因此Service与访问者之间也无法进行通信交换数据 * * 当开发Service类时,该Service类必须提供一个IBinder onBind(Intent intent)方法, * 当Activity绑定了本地Service时,IBinder onBind(Intent intent)方法所返回的IBinder对象会传给 * ServiceConnection对象里面的onServiceConnected(ComponentName, IBinder service)方法的service参数, * 这样访问者就可以通过该IBinder对象与Service通信了 * * 而bindService()可以用来绑定本地Service并与之通信 * 完整方法:bindService(Intent service, ServiceConnection conn, int flags) * 这里详细解释一下第二个参数(个人见解<不一定对>) * 第二个参数是一个ServiceConnection对象,该对象用于监听访问者与Service之间的连接情况 * 当访问者与Service之间连接成功时将回调该ServiceConnection对象的onServiceConnected(ComponentName,IBinder Service)方法; * 当Service所在的宿主进程由于异常或者其他原因终止,导致该Service与访问者之间断开连接时, * 回调该ServiceConnection对象的onServiceDisconnected(ComponentName name)方法。 * 通俗点讲就是: * service与activity进行通讯的要使用bindService(Intent service, ServiceConnection conn, int flags)方法 * 而这个方法中包含一个ServiceConnection conn参数,所以要在activity中声明这个类,并且重写他的两个方法 * onServiceConnected()和onServiceDisconnected()方法,这两个方法分别在连接到Service和断开与Service连接时回调, */public class FirstService extends Service {    private int count;    private boolean quit;    public class MyBinder extends Binder{            public int getCount(){                return count;            }    }    private MyBinder binder = new MyBinder();    @Nullable    @Override    public IBinder onBind(Intent intent) {        Log.i("FirstService", "onBind");        return binder;    }    @Override    public void onCreate() {        Log.i("FirstService", "onCreate");        new Thread(){            @Override            public void run() {                while (!quit){                    try {                        sleep(2000);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    count++;                }            }        }.start();        super.onCreate();    }    @Override    public boolean onUnbind(Intent intent) {        Log.i("FirstService", "onUnbind");        return true;    }    @Override    public void onRebind(Intent intent) {        super.onRebind(intent);        Log.i("FirstService", "onRebind");    }    @Override    public void onDestroy() {        Log.i("FirstService", "onDestroy");        super.onDestroy();        this.quit = true;    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.i("FirstService", "onStartCommand");        return super.onStartCommand(intent, flags, startId);    }}

xml文件:

activity_main

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <Button        android:id="@+id/btnStart"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="启动" />    <Button        android:id="@+id/btnStop"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="停止"/>    <Button        android:id="@+id/btnBindService"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="绑定Service" />    <Button        android:id="@+id/btnUnBindService"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="解除绑定Service"/>    <Button        android:id="@+id/btnGetCount"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="获取Service的Count" /></LinearLayout>

mainifest

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.zhang.service">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity            android:name=".MainActivity"            android:label="@string/app_name"            android:theme="@style/AppTheme">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name=".FirstService">        </service>    </application></manifest>

总结:
当Activity调用Binder()绑定一个已经启动的Service时,系统只是把Service内部IBinder对象传给Activity,并不会把该Service生命周期完全“绑定”到该Activity,因此,当Activity调用ubBindService()方法取消与该Service的绑定时,也只是切断该Activity与Service之间的关联,并不能停止该Service组件

图片:
绑定本地Service并与之通信启动-停止-启动-停止

1

绑定本地Service并与之通信启动–绑定-解绑-绑定

2

绑定本地Service并与之通信绑定

3

0 0
原创粉丝点击