在做項目的時候會有強制下線的功能,彈出一個強制退出登錄的彈窗,點擊跳轉到登錄頁面。
激活強制退出登錄的方式就是在請求接口的時候,根據接口返回的code等於特定的值來激活。
定義一個工具類,在每次請求接口的時候對將參數傳入工具類
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
public class DialogUtils {
public static void showLoginout(final Context mContext, final int code) {
final Dialog mDialog;
mDialog = new Dialog(mContext, R.style.WycDialogStyle);
mDialog.setContentView(R.layout.dialog_base2);
mDialog.setCanceledOnTouchOutside(false); // 觸摸黑色不能取消
mDialog.setCancelable(false); // 返回按鈕不能取消
TextView messageText = mDialog.findViewById(R.id.tv_message);
if (code == 15) {
messageText.setText("登錄失效,請重新登錄!");
}
try {
mDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
mDialog.findViewById(R.id.tv_yes).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mDialog.dismiss();
}
});
}
}
但是有時候一個界面會有衆多的請求,因此就會出現多個彈窗,思考解決方法想到可以把它定
義爲靜態的,並且是單例的模式,就像這樣的
private static Dialog mDialog;
public static Dialog dialogInit(Context mContext) {
if (mDialog == null) {
synchronized (Dialog.class) {
if (mDialog == null) {
mDialog = new Dialog(mContext, R.style.WycDialogStyle);
}
}
}
return mDialog;
}
但是在彈出一次之後在跳轉頁面發現彈窗不再彈出了,還出現錯誤日誌:
java.lang.IllegalStateException: View DecorView@3a7b850[] has already been added to the window manager...
於是通過查到資料詳細的瞭解到Dialog是必須依附在Activity上的,於是嘗試判斷上下文
是否一致,來創建或者引用Dialog變量,發現還是有問題,再琢磨想到可以通過判斷加一個變量值
一旦彈出推出框就不再彈出,然後在BaseActivity中的onCreate中重新初始化isShow爲true
public class DialogUtils {
public static boolean isShow = true;
public static void showLoginout(final Context mContext, final int code) {
if (isShow) {
isShow = false;
final Dialog mDialog;
mDialog = new Dialog(mContext, R.style.WycDialogStyle);
mDialog.setContentView(R.layout.dialog_base2);
mDialog.setCanceledOnTouchOutside(false); // 觸摸黑色不能取消
mDialog.setCancelable(false); // 返回按鈕不能取消
TextView messageText = mDialog.findViewById(R.id.tv_message);
if (code == 15) {
messageText.setText("登錄失效,請重新登錄!");
}
try {
mDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
mDialog.findViewById(R.id.tv_yes).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mDialog.dismiss();
}
});
}
}
}
至此,問題解決了