Android番外篇 Activity绑定Service工具类 含自动重连功能

一、自动重连工具类

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

/**
 * @ClassName : ServiceBindHelper.java
 * @Function : 服务绑定助手
 * @Description :
 * @Idea :
 * {@link  }
 * @Encourage :Do everything you can right now, and then decide.
 *              全力以赴,历而后择。
 * @date : 2021/8/30
 */
public class ServiceBindHelper {
    private static final String TAG = "ServiceBindHelper";
    // 绑定策略
    private BindPolicy mBindPolicy;
    private Intent mIntent;
    private final Context mContext;
    // 服务连接
    private ServiceConnection mUserCallback;
    // MSG 重试绑定服务
    private static final int MSG_RETRY_BIND_SERVICE = 201;

    /**
     * The constant STATE_DISCONNECTED.
     * 常量 STATE_DISCONNECTED
     */
    public static final int STATE_DISCONNECTED = 0;
    /**
     * The constant STATE_CONNECTING.
     * 常量 STATE_CONNECTING
     */
    public static final int STATE_CONNECTING = 1;
    /**
     * The constant STATE_CONNECTED.
     * 常量 STATE_CONNECTED
     */
    public static final int STATE_CONNECTED = 2;
    /**
     * The constant STATE_RETRYING.
     * 常量 STATE_RETRYING
     */
    public static final int STATE_RETRYING = 3;

    //连接状态
    private int mConnectionState;
    //重试次数
    private int mRetryCount;

    private Handler mHandler;

    //服务连接
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected() called with: name = [" + name + "], service = [" + service + "]");
            if (mConnectionState != STATE_CONNECTED) {
                mConnectionState = STATE_CONNECTED;
                mUserCallback.onServiceConnected(name, service);
            }
        }

        /**
         * 在服务断开时
         * @param name 组件名称
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected() called with: name = [" + name + "]");
            mUserCallback.onServiceDisconnected(name);
            mContext.unbindService(mServiceConnection);
            mConnectionState = STATE_DISCONNECTED;
            //请求自动重新绑定
            requestAutoReBind();
        }
    };

    /**
     * Instantiates a new Service bind helper.
     * 实例化一个新的 Service 绑定助手
     * @param context      the context       上下文环境
     * @param userCallback the user callback
     */
    public ServiceBindHelper(Context context,
                             ServiceConnection userCallback) {
        // DefaultBindPolicy :默认绑定策略
        this(context, userCallback, new DefaultBindPolicy());
    }

    /**
     * Instantiates a new Service bind helper.
     * 实例化一个新的 Service 绑定助手
     * @param context      the context
     * @param userCallback the user callback
     * @param bindPolicy   the bind policy
     */
    public ServiceBindHelper(Context context, ServiceConnection userCallback,
                             BindPolicy bindPolicy) {
        Log.d(TAG, "ServiceBindHelper() called with: context = [" + context + "], userCallback = [" + userCallback
                + "], bindPolicy = [" + bindPolicy + "]");
        if (context == null) {
            throw new NullPointerException("context is null");
        }
        if (userCallback == null) {
            throw new NullPointerException("userCallback is null");
        }
        if (bindPolicy == null) {
            throw new NullPointerException("bindPolicy is null");
        }
        mContext = context;
        mUserCallback = userCallback;
        mBindPolicy = bindPolicy;
        initHandler();
    }

    private void initHandler() {
        if (mHandler == null) {
            mHandler = new Handler(mContext.getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MSG_RETRY_BIND_SERVICE:
                            if (reBind()) {
                                mRetryCount = 0;
                            } else {
                                mRetryCount++;
                                requestAutoReBind();
                            }
                            break;
                        default:
                            break;
                    }
                }
            };
        }
    }


    /**
     * Bind.
     *
     * @param intent the intent
     */
    public void bind(Intent intent) {
        Log.d(TAG, "bind() called with: intent = [" + intent + "]");
        if (intent == null) {
            throw new NullPointerException("intent is null");
        }
        if (mConnectionState != STATE_DISCONNECTED) {
            Log.e(TAG, "bind: isBinding");
            return;
        }
        mConnectionState = STATE_CONNECTING;
        mIntent = intent;
        boolean bindRes = mContext.bindService(intent, mServiceConnection, mBindPolicy.getBindFlags());
        if (!bindRes) {
            requestAutoReBind();
        }
    }

    /**
     * Unbind.
     * 解绑
     */
    public void unbind() {
        mHandler.removeCallbacksAndMessages(null);
        mContext.unbindService(mServiceConnection);
        mConnectionState = STATE_DISCONNECTED;
        mIntent = null;
    }

    /**
     * 请求自动重新绑定
     */
    private void requestAutoReBind() {
        Log.d(TAG, "requestAutoReBind() called");
        if (mBindPolicy.isAutoReBind() && mRetryCount < mBindPolicy.getRetryLimit()) {
            if (mHandler.hasMessages(MSG_RETRY_BIND_SERVICE)) {
                mHandler.removeMessages(MSG_RETRY_BIND_SERVICE);
            }
            mHandler.sendEmptyMessageDelayed(MSG_RETRY_BIND_SERVICE,
                    mBindPolicy.getReBindInterval());
        }
    }

    /**
     * 重新绑定
     * @return 链接状态 - ture  断开状态 - false
     */
    private boolean reBind() {
        Log.d(TAG, "reBind() called");
        if (mConnectionState == STATE_CONNECTED) {
            return true;
        }
        mConnectionState = STATE_RETRYING;
        boolean bindRes = mContext.bindService(mIntent, mServiceConnection, mBindPolicy.getBindFlags());
        Log.d(TAG, "reBind() returned: " + bindRes);
        return false;
    }

    /**
     * Gets connection state.
     * 获取连接状态
     * @return the connection state 连接状态
     */
    public int getConnectionState() {
        return mConnectionState;
    }

    /**
     * The type Bind policy.
     * 类型绑定策略
     */
    public abstract static class BindPolicy {

        /**
         * Gets re bind interval.
         *
         * @return the re bind interval
         */
        public abstract long getReBindInterval();

        /**
         * Gets bind flags.
         *
         * @return the bind flags
         */
        public abstract int getBindFlags();

        /**
         * Is auto re bind boolean.
         *
         * @return the boolean
         */
        public abstract boolean isAutoReBind();

        /**
         * Gets retry limit.
         *
         * @return the retry limit
         */
        public abstract int getRetryLimit();
    }

    /**
     * The type Default bind policy.
     */
    public static class DefaultBindPolicy extends BindPolicy {

        /**
         * The constant RETRY_LIMIT.
         */
        public static final int RETRY_LIMIT = 3;
        private static final int RETRY_INTERVAL = 2000;


        @Override
        public long getReBindInterval() {
            return RETRY_INTERVAL;
        }

        @Override
        public int getBindFlags() {
            return Context.BIND_AUTO_CREATE;
        }

        @Override
        public boolean isAutoReBind() {
            return true;
        }

        @Override
        public int getRetryLimit() {
            return RETRY_LIMIT;
        }
    }
}

二、实战使用

public class Test {
	private final Context mContext;
    private ServiceBindHelper mServiceBindHelper;

	...
	
	private final ServiceConnection mServiceConnection = new ServiceConnection() {
	    @Override
	    public void onServiceConnected(ComponentName name, IBinder service) {
	            Log.d(TAG, "onServiceConnected() called with: name = [" + name + "], service = [" + service + "]");
	    }
	
	    @Override
	    public void onServiceDisconnected(ComponentName name) {
	        Log.d(TAG, "onServiceDisconnected() called with: name = [" + name + "]");
	    }
	};

    private void bind() {
        mServiceBindHelper = new ServiceBindHelper(mContext,mServiceConnection);
        Intent intent = new Intent();
        intent.setAction(..);
        intent.setComponent(new ComponentName(..., ...));
        mServiceBindHelper.bind(intent);
    }
    
    public void destory() {
        Log.d(TAG, "destory() called");
        mServiceBindHelper.unbind();
        mServiceBindHelper = null;
        sInstance = null;
    }

	....
	
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

其子昱舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值