安卓绑定本地服务Service并与之通信


效果


代码

1.主Activity

package com.example.test2.myapplication.service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.test2.myapplication.R;

/**
 * Created by Derek on 2017/2/18.
 * 绑定本地服务Service并与之通信
 */

public class BindServiceTest extends AppCompatActivity implements View.OnClickListener {

    private Button bind;
    private Button unbind;
    private Button getservicestatus;

    BindService.MyBinder binder;
    ServiceConnection serviceConnection = new ServiceConnection() {
        //Activityservice连接成功时,回调该方法
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("GsonUtils", "onServiceConnected");
            binder = (BindService.MyBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("GsonUtils", "onServiceDisconnected");

        }
    };
    Intent intent;
    private TextView textView8;
    private TextView count;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bindservicetest);
        initView();
//        intent = new Intent();

        intent = new Intent(this, BindService.class);
        intent.setAction("com.example.test2.myapplication.service.Bind_Service");
    }

    private void initView() {
        bind = (Button) findViewById(R.id.bind);
        unbind = (Button) findViewById(R.id.unbind);
        getservicestatus = (Button) findViewById(R.id.getservicestatus);

        bind.setOnClickListener(this);
        unbind.setOnClickListener(this);
        getservicestatus.setOnClickListener(this);
        textView8 = (TextView) findViewById(R.id.textView8);
        textView8.setOnClickListener(this);
        count = (TextView) findViewById(R.id.count);
        count.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bind:
                //绑定Service
                bindService(intent, serviceConnection, BIND_AUTO_CREATE);
                break;
            case R.id.unbind:
                //解除绑定Service
                unbindService(serviceConnection);
                break;
            case R.id.getservicestatus:
                //不能直接设置int的值
                //count.setText(binder.getCount());
                //获取并显示Servicecount                count.setText("Servicecount值为:" +binder.getCount());
                Toast.makeText(this, "Servicecount值为:" + binder.getCount(), Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

2.服务

package com.example.test2.myapplication.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 Derek on 2017/2/18.
 */

public class BindService extends Service {

    int count;
    boolean quit;

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

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

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("GsonUtils", "onBind");
        //返回IBinder对象
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //启动一条线程,动态的修改count的状态值
        new Thread() {
            @Override
            public void run() {
                super.run();
                while (!quit) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        }.start();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("GsonUtils", "onUnbind");
        return true;
    }

    //service被关闭时
    @Override
    public void onDestroy() {
        super.onDestroy();
        //停止线程任务的执行
        this.quit = true;
        Log.d("GsonUtils", "onDestroy");
    }
}

布局xml

<?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/bind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="bind"/>
    <Button
        android:id="@+id/unbind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="unbind"/>
    <Button
        android:id="@+id/getservicestatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="getservicestatus"/>
    <TextView
        android:id="@+id/textView8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Servicecount值动态值"
        android:textSize="26dp"/>
    <TextView
        android:textColor="#f00"
        android:id="@+id/count"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="count"
        android:textSize="26dp"/>

</LinearLayout>

AndroidManifest.xml

<service android:name="com.example.test2.myapplication.service.BindService">
    <intent-filter>
        <action android:name="com.example.test2.myapplication.service.Bind_Service"></action>
    </intent-filter>
</service>

。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值