IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android Activity绑定Service工具类 含自动重连功能 记录备用 -> 正文阅读

[移动开发]Android Activity绑定Service工具类 含自动重连功能 记录备用

ServiceBindHelper

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;


/**
 * The type Service bind helper.
 */
public class ServiceBindHelper {
    private static final String TAG = "ServiceBindHelper";
    private BindPolicy mBindPolicy;
    private Intent mIntent;
    private final Context mContext;
    private ServiceConnection mUserCallback;

    private static final int MSG_RETRY_BIND_SERVICE = 201;

    /**
     * The constant STATE_DISCONNECTED.
     */
    public static final int STATE_DISCONNECTED = 0;
    /**
     * The constant STATE_CONNECTING.
     */
    public static final int STATE_CONNECTING = 1;
    /**
     * The constant STATE_CONNECTED.
     */
    public static final int STATE_CONNECTED = 2;
    /**
     * The constant 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);
            }
        }

        @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.
     *
     * @param context      the context
     * @param userCallback the user callback
     */
    public ServiceBindHelper(Context context,
            ServiceConnection userCallback) {
        this(context, userCallback, new DefaultBindPolicy());
    }

    /**
     * Instantiates a new Service bind helper.
     *
     * @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());
        }
    }

    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;
        }
    }

}

使用DEMO

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;
    }

	....
	
}
  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-08-29 09:28:21  更:2021-08-29 09:30:00 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 13:38:55-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码