Android token失效统一跳转登陆界面,基于okhttp+广播通信

huatechinfo
发布于 2021-3-31 13:50
浏览
0收藏

第一步找个Activity注册广播监听

一般选择app主框架activity

OkHttp拦截器写法

public class TokenInterceptor implements Interceptor {
 
    private static final Charset UTF8 = Charset.forName("UTF-8");
 
    private Context mContext;
 
    public TokenInterceptor(Context co){
        mContext = co;
    }
 
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response originalResponse = chain.proceed(request);
        ResponseBody responseBody = originalResponse.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
 
        //bodyString: {"error":"Token已经失效,或账号在别处登录!","status":-100}
        String bodyString = buffer.clone().readString(charset);
        BaseData data = new Gson().fromJson(bodyString, BaseData.class);
 
        /***************************************/
        if (data.getStatus() == -100){
            //token过期 发通知
            Intent intents = new Intent("TOKEN_INVALID");
            intents.putExtra("message", data.getError());
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intents);
        }
 
        // otherwise just pass the original response on
        return originalResponse;
    }
}


 

监听部分

private BroadcastReceiver receiver;
private LocalBroadcastManager broadcastManager;
 
 
@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContxt = this;
        registerTokenListener();
}
 
private void registerTokenListener(){
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Bundle bundle = intent.getExtras();
                CustmerToast.makeText(mContxt, bundle.getString("message")).show();
                startActivity(new Intent(mContxt, LoginActivity.class));
                finish();
            }
        };
        broadcastManager = LocalBroadcastManager.getInstance(mContxt);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("TOKEN_INVALID"); //自定义监听的事件key
        broadcastManager.registerReceiver(receiver, intentFilter);
        
        //为HttpClient添加拦截器
        OkHttpClientManager.getInstance().addIntercept(new TokenInterceptor(mContxt));
 }


我代码中的OkHttpClientManager

import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;
 
import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.squareup.okhttp.*;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
 
public class OkHttpClientManager{
    private static OkHttpClientManager mInstance;
    private OkHttpClient mOkHttpClient;
    private Handler mDelivery;
    private Gson mGson;
 
    private static final String TAG = OkHttpClientManager.class.getSimpleName();
 
    private OkHttpClientManager(){
        mOkHttpClient = new OkHttpClient();
        //cookie enabled
        mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(20, TimeUnit.SECONDS);
        mDelivery = new Handler(Looper.getMainLooper());
        mGson = new Gson();
    }
 
    public static void addIntercept(Interceptor interceptor){
        if(mInstance != null){
            mInstance.mOkHttpClient.interceptors().add(interceptor);
        }
    }
 
    public static OkHttpClientManager getInstance()
    {
        if (mInstance == null)
        {
            synchronized (OkHttpClientManager.class)
            {
                if (mInstance == null)
                {
                    mInstance = new OkHttpClientManager();
                }
            }
        }
        return mInstance;
    }
}


网上没找到现成的,后来尝试使用广播的方式实现,如果有问题欢迎在评论区留言  

夏天快乐^_^
————————————————
版权声明:本文为博主「长枫丶」的原创文章

分类
收藏
回复
举报
回复
    相关推荐