绑定本地Service并与之通信

58 篇文章 1 订阅
45 篇文章 1 订阅

    当程序通过startService()和stopService()启动、关闭Service时,Service与访问者之间基本上不存在太多的关联,一次Service和访问者之间无法进行通信和数据传递。

    如果Service和访问者之间需要进行方法调用或数据传递,则使用bindService()和unbindService()方法启动、关闭服务。


    Context的bindService()方法的完整方法签名为:

bindService(Intent service, ServiceConnection conn, int flags)

    三个参数用法如下:

    1.service:通过Intent指定要启动的Service。

    2.conn:该参数是一个ServiceConnection对象,用于监听访问者与Service之间的连接情况。连接成功时,将回调该对象的onServiceConnected(ComponentName name, IBinder service)方法;当断开连接时,回调该对象的onServiceDisconnected(ComponentName name)方法。

    3.flags:指定绑定时是否自动创建Service(如果Service还未创建)。0为不自动创建,BIND_AUTO_CREATE为自动创建。


    注意到ServiceConnection对象的onServiceConnected方法中有一个IBinder对象,该对象实现与被绑定Service之间的通信。

    

    下面给出一个实例:

    工程结构:

    


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.leidong.bindservice">

    <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">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".BindService">
        </service>
    </application>

</manifest>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#2b2b2b">

    <!--bind按钮-->
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5pt"
        android:layout_marginRight="5pt"
        android:layout_marginTop="10pt"
        android:text="B I N D"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:background="#696969"
        android:id="@+id/bindButton"
        android:layout_gravity="center_horizontal" />

    <!--unbind按钮-->
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5pt"
        android:layout_marginRight="5pt"
        android:layout_marginTop="10pt"
        android:text="U N B I N D"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:background="#696969"
        android:id="@+id/unbindButton"
        android:layout_gravity="center_horizontal" />

    <!--getServiceStatus按钮-->
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5pt"
        android:layout_marginRight="5pt"
        android:layout_marginTop="10pt"
        android:text="G E T    S E R V I C E    S T A T U S"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:background="#696969"
        android:id="@+id/getServiceStatusButton"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

MainActivity.java

package com.example.leidong.bindservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

/**
 * Created by Lei Dong on 2016/9/5.
 */

public class MainActivity extends Activity {
    //声明按钮
    Button bind;
    Button unbind;
    Button getServiceStatus;

    //保持所启动的Service的IBinder对象
    BindService.MyBinder myBinder;

    //定义一个ServiceConnection对象
    private ServiceConnection connection = new ServiceConnection() {
        //连接成功时
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            System.out.println("~~~~~Connected~~~~~");
            //获取Service的onBind方法返回的MyBinder对象
            myBinder = (BindService.MyBinder) iBinder;
        }

        //连接失败时
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            System.out.println("~~~~~Disconnected~~~~~");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //获取程序界面中的bind、unbind、getServiceStatus按钮
        bind = (Button)findViewById(R.id.bindButton);
        unbind = (Button)findViewById(R.id.unbindButton);
        getServiceStatus = (Button)findViewById(R.id.getServiceStatusButton);

        //创建启动Service的Intent
        final Intent intent = new Intent(MainActivity.this, BindService.class);

        //监听bind按钮点击
        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //绑定指定Service
                bindService(intent, connection, BIND_AUTO_CREATE);
            }
        });

        //监听unbind按钮点击
        unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //解除绑定Service
                unbindService(connection);
            }
        });

        //监听getServiceStatus按钮点击
        getServiceStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取并显示Service的count值
                Toast.makeText(MainActivity.this,
                        "Service的count值为:" + myBinder.getCount(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

BindService.java

package com.example.leidong.bindservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
 * Created by Lei Dong on 2016/9/5.
 */
public class BindService extends Service {
    private int count;
    private boolean quitFlag;

    //定义onBinder方法所返回的对象
    private MyBinder myBinder = new MyBinder();

    //通过继承Binder来实现IBinder类
    public class MyBinder extends Binder {
        public int getCount(){
            //获取Service的运行状态
            return count;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("~~~~~Service is binded~~~~~");
        //返回IBinder对象
        return myBinder;
    }

    @Override
    public void onCreate(){
        super.onCreate();
        System.out.println("~~~~~Service is created~~~~~");
        //启动一条线程,动态地修改count状态值
        new Thread(){
            @Override
            public void run(){
                while(!quitFlag){
                    try{
                        Thread.sleep(1000);
                    }catch (InterruptedException e)
                    {

                    }
                    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.quitFlag = true;
        System.out.println("~~~~~Service is destroyed~~~~~");
    }
}

AVD效果:



点击BIND按钮,LogCat效果:



点击UNBIND按钮,LogCat效果:



点击GET SERVICE STATUS按钮,LogCat效果:


    


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值