package xn.hxp.ui; import android.app.AlertDialog; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.hardware.usb.UsbManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.EditText; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewbinding.ViewBinding; import com.blankj.utilcode.util.ActivityUtils; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.LogUtils; import com.blankj.utilcode.util.SPUtils; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.RequestOptions; import com.king.zxing.util.CodeUtils; import com.kongzue.dialogx.dialogs.PopTip; import com.lztek.toolkit.Lztek; import com.rc.core.ui.activity.BaseActivity; import com.rc.httpcore.HttpClient; import com.rc.httpcore.HttpConfig; import com.rc.httpcore.client.ApiRepository; import com.rc.httpcore.client.HttpTool; import com.rc.httpcore.exception.NetException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import io.reactivex.rxjava3.functions.Consumer; import kotlin.Unit; import kotlin.jvm.functions.Function1; import retrofit2.HttpException; import xn.hxp.R; import xn.hxp.app.ChemicalApp; import xn.hxp.databinding.ActivityMainBinding; import xn.hxp.receiver.TimeTickReceiver; import xn.hxp.receiver.UsbReceiver; import xn.hxp.ui.adapter.CabinetAdapter; import xn.hxp.ui.discard.LedgerActivity; import xn.hxp.ui.discard.WasteChemicalsActivity; import xn.hxp.ui.inquiry.InquiryActivity; import xn.hxp.ui.login.FaceLoginActivity; import xn.hxp.ui.login.FacialCardActivity; import xn.hxp.ui.login.ScanLoginActivity; import xn.hxp.ui.login.SwipeActivity; import xn.hxp.ui.plan.PlanAddActivity; import xn.hxp.ui.plan.already.AlreadyActivity; import xn.hxp.ui.still.ChemicalsAlsoActivity; import xn.hxp.ui.still.MsdsActivity; import xn.hxp.ui.uses.UseActivity; import xn.hxp.ui.uses.WarningEventsActivity; import xn.hxp.ui.warehousing.ChemicalLabelingActivity; import xn.hxp.utils.RelativeLayoutDebouncer; import xn.hxp.utils.SharedPreferencesHelper; import xn.hxp.utils.TimeUpdater; import xn.hxp.utils.UiManager; import xn.hxp.weidith.CustomDialog; import xn.hxp.weidith.PlanDialog; public class MainActivity extends BaseActivity { private ActivityMainBinding viewBinding; private TimeUpdater timeUpdater; private CabinetAdapter mAdapter; private int currentPosition = 0; private RecyclerView recyclerView; private UsbReceiver mUsbReceiver; private Lztek mLztek; private String mDeviceNum; private List faceList; private String mLoginType; private int mCounter = 0; private int MAX_TIME = 60; private static final int WHAT_COUNT_DOWN = 1; private LinearLayoutManager layoutManager; private Handler handlerBanner; private Runnable updateRunnable; private boolean isUpdating = false; private TimeTickReceiver timeTickReceiver = new TimeTickReceiver(); private PlanDialog planDialog; private CountDownTimer heartbeatCdTimer; @Override protected void onResume() { super.onResume(); if (ChemicalApp.userData != null) { viewBinding.inc.userLogin.setVisibility(View.GONE); viewBinding.inc.loggedIn.setVisibility(View.VISIBLE); viewBinding.inc.tvName.setText(ChemicalApp.userData.userName); Glide.with(this) .load(HttpConfig.Companion.getAPI_BASE_IMG_URL() + ChemicalApp.userData.avatar) .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)) .into(viewBinding.inc.imageName); viewBinding.inc.imgE.setBackgroundResource(R.mipmap.cshrk_dl_tc); MAX_TIME = ChemicalApp.confs.getSignOutTime(); mCountDownHandler.removeMessages(WHAT_COUNT_DOWN); mCountDownHandler.sendEmptyMessage(WHAT_COUNT_DOWN); } else { viewBinding.inc.loggedIn.setVisibility(View.GONE); viewBinding.inc.userLogin.setVisibility(View.VISIBLE); viewBinding.inc.imgE.setBackgroundResource(R.mipmap.icon_login_img); } if (mAdapter.getData() != null && mAdapter.getData().size() > 1) { startUpdating(); } timeUpdater.startUpdating(); getCabinetIn(); basicConf(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(timeTickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK)); viewBinding.versionName.setText("版本号:" + AppUtils.getAppVersionName()); viewBinding.test.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!AppUtils.isAppDebug()) { showTextInputDialog("请输入内容", new TextInputCallback() { @Override public void onInput(String input) { if (input != null) { if (!input.isEmpty()) { try { if ("admin@098&".equals(input)) { ActivityUtils.startActivity(SettingActivity.class); finish(); } else { SettingsBean urlBase = SharedPreferencesHelper.INSTANCE.getUrlBase(MainActivity.this); if (urlBase != null && urlBase.getPwd() != null) { if (input.equals(urlBase.getPwd())) { ActivityUtils.startActivity(SettingActivity.class); finish(); } else { showToast("密码错误"); } } } } catch (Exception e) { ActivityUtils.startActivity(SettingActivity.class); finish(); } } } else { showToast("用户取消了输入"); } } }); } else { ActivityUtils.startActivity(SettingActivity.class); finish(); } } }); viewBinding.inc.bleIV.setVisibility(View.VISIBLE); String sppMac = SPUtils.getInstance().getString("sppMac", ""); if (sppMac == null || TextUtils.isEmpty(sppMac)) { viewBinding.inc.bleIV.setBackgroundResource(R.drawable.ic_ble_unconnected); PopTip.show("未配置蓝牙称设备!").showLong(); } // 心跳上报 heartbeatCdTimer = new CountDownTimer(20000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { AsyncTask.execute(() -> { try { HttpTool.heartbeat(); } catch (Exception e) { LogUtils.e(Log.getStackTraceString(e)); } }); heartbeatCdTimer.start(); } }; heartbeatCdTimer.start(); } @Override public boolean dispatchKeyEvent(KeyEvent event) { return super.dispatchKeyEvent(event); } @Override protected void onStop() { super.onStop(); LogUtils.i("============onStop"); } @Override protected void onPause() { LogUtils.i("============onPause"); try { stopUpdating(); timeUpdater.stopUpdating(); LogUtils.i("========UI在刷新停止"); mCountDownHandler.removeMessages(WHAT_COUNT_DOWN); mCountDownHandler.removeCallbacksAndMessages(null); } catch (Exception e) { } super.onPause(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } private void getCabinetIn() { showLoading("查询中..."); ApiRepository.INSTANCE.getCabinetBySubId(ChemicalApp.subjectId) .subscribe(data -> { dismissLoading(); mAdapter.setNewInstance(new ArrayList<>(data)); if (mAdapter.getData() != null && mAdapter.getData().size() > 1) { handlerBanner = new Handler(Looper.getMainLooper()); updateRunnable = new Runnable() { @Override public void run() { int currentPosition = layoutManager.findFirstVisibleItemPosition(); if (currentPosition != RecyclerView.NO_POSITION) { int nextPosition = (currentPosition + 1) % mAdapter.getItemCount(); recyclerView.smoothScrollToPosition(nextPosition); } if (isUpdating) { handlerBanner.postDelayed(this, 5000); } } }; startUpdating(); } }, throwable -> { dismissLoading(); throwable.printStackTrace(); }); } private void getUserIds() { if (ChemicalApp.subjectId != null) { showLoading("查询中..."); ApiRepository.INSTANCE.getUserIds(ChemicalApp.subjectId) .subscribe(data -> { dismissLoading(); faceList = data; }, throwable -> { dismissLoading(); }); } } private void initAdapter() { recyclerView = viewBinding.relView; layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(mAdapter); recyclerView.setOnTouchListener((v, event) -> true); mAdapter.setOnItemChildClickListener((adapter, view, position) -> { if (ChemicalApp.userData != null) { Map map = new HashMap<>(); map.put("logIn", 1); if (view.getId() == R.id.lingOne) { map.put("cabinetId", mAdapter.getData().get(position).getCabinetId()); map.put("doorId", mAdapter.getData().get(position).getCabinetDoorVoList().get(0).getDoorUniqueId()); UiManager.INSTANCE.switcher(this, map, InquiryActivity.class); } else if (view.getId() == R.id.lintTwo) { map.put("cabinetId", mAdapter.getData().get(position).getCabinetDoorVoList().get(1).getCabinetId()); map.put("doorId", mAdapter.getData().get(position).getCabinetDoorVoList().get(1).getDoorUniqueId()); UiManager.INSTANCE.switcher(this, map, InquiryActivity.class); } else if (view.getId() == R.id.lintThree) { map.put("cabinetId", mAdapter.getData().get(position).getCabinetDoorVoList().get(2).getCabinetId()); map.put("doorId", mAdapter.getData().get(position).getCabinetDoorVoList().get(2).getDoorUniqueId()); UiManager.INSTANCE.switcher(this, map, InquiryActivity.class); } else if (view.getId() == R.id.lintFour) { map.put("cabinetId", mAdapter.getData().get(position).getCabinetDoorVoList().get(3).getCabinetId()); map.put("doorId", mAdapter.getData().get(position).getCabinetDoorVoList().get(3).getDoorUniqueId()); UiManager.INSTANCE.switcher(this, map, InquiryActivity.class); } else if (view.getId() == R.id.imgViews) { map.put("cabinetId", "a"); map.put("doorId", "a"); UiManager.INSTANCE.switcher(this, map, InquiryActivity.class); } } else { basicConfLog(); } }); } private void startUpdating() { if (!isUpdating) { isUpdating = true; handlerBanner.post(updateRunnable); } } private void stopUpdating() { if (isUpdating) { isUpdating = false; handlerBanner.removeCallbacks(updateRunnable); } } private void handleScanEvent(String cont) { // Implementation remains similar to Kotlin version } private void registerUsbBroadcast() { if (mUsbReceiver == null) { IntentFilter filter = new IntentFilter(); filter.addAction(UsbReceiver.ACTION_USB_PERMISSION); filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); filter.addAction(UsbReceiver.ACTION_USB_STATE); mUsbReceiver = new UsbReceiver(); registerReceiver(mUsbReceiver, filter); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(timeTickReceiver); try { timeUpdater.stopUpdating(); stopUpdating(); mCountDownHandler.removeMessages(WHAT_COUNT_DOWN); mCountDownHandler.removeCallbacksAndMessages(null); } catch (Exception e) { } } private void subAddData() { mLztek = Lztek.create(this); String toUpperCase = mLztek.getEthMac().toUpperCase(); mDeviceNum = toUpperCase.replace(":", ""); ApiRepository.INSTANCE.monitor(mDeviceNum) .subscribe(data -> { }, this::showNetError); } private void basicConf() { ApiRepository.INSTANCE.basicConfig(ChemicalApp.subjectId) .subscribe(data -> { ChemicalApp.confs = data; mLoginType = data.getLoginType(); if (data.getLevelName() != null) { String result = data.getLevelName().chars() .mapToObj(c -> String.valueOf((char) c)) .reduce("", (s1, s2) -> s1 + "\n" + s2); viewBinding.tvNoName.setText(result); GradientDrawable shapes = new GradientDrawable(); shapes.setShape(GradientDrawable.RECTANGLE); shapes.setColor(Color.parseColor(data.getLevelColor())); shapes.setCornerRadius(5f); viewBinding.tvNoName.setBackground(shapes); } else { viewBinding.tvNoName.setVisibility(View.GONE); } viewBinding.subName.setText(data.getSubName()); viewBinding.inc.deptName.setText(data.getDeptName()); Glide.with(this) .load(HttpConfig.Companion.getAPI_BASE_IMG_URL() + data.getCircularLogo()) .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)) .into(viewBinding.inc.circularLogo); }, this::showNetError); } private void basicConfLog() { ApiRepository.INSTANCE.basicConfig(ChemicalApp.subjectId) .subscribe(data -> { LogUtils.json(data); ChemicalApp.confs = data; mLoginType = data.getLoginType(); if (mLoginType == null) { customDialogView(2, "登录方式配置有误"); } else { if (mLoginType.contains("4")) { UiManager.INSTANCE.switcher(this, FacialCardActivity.class); } else { Map map = new HashMap<>(); if (mLoginType.length() == 1) { switch (mLoginType) { case "1": map.put("faceList", faceList.toString()); map.put("mtypes", "1"); UiManager.INSTANCE.switcher(this, map, FaceLoginActivity.class); break; case "2": map.put("mtypes", "1"); UiManager.INSTANCE.switcher(this, map, SwipeActivity.class); break; default: map.put("mtypes", "1"); UiManager.INSTANCE.switcher(this, map, ScanLoginActivity.class); break; } } else { String[] array = mLoginType.split(","); if (array.length == 2) { if (mLoginType.equals("1,2") || mLoginType.equals("2,1")) { map.put("faceList", faceList.toString()); map.put("mtypes", "4"); UiManager.INSTANCE.switcher(this, map, FaceLoginActivity.class); } else if (mLoginType.equals("1,3") || mLoginType.equals("3,1")) { map.put("faceList", faceList.toString()); map.put("mtypes", "5"); UiManager.INSTANCE.switcher(this, map, FaceLoginActivity.class); } else if (mLoginType.equals("2,3") || mLoginType.equals("3,2")) { map.put("mtypes", "6"); UiManager.INSTANCE.switcher(this, map, SwipeActivity.class); } else { showToast("登录方式" + mLoginType); } } else { try { map.put("mtypes", "0"); map.put("faceList", faceList.toString()); UiManager.INSTANCE.switcher(this, map, FaceLoginActivity.class); } catch (Exception e) { map.put("mtypes", "0"); UiManager.INSTANCE.switcher(this, map, SwipeActivity.class); } } } } } }, this::showNetError); } private void customDialogView(int types, String msg) { CustomDialog customDialog = new CustomDialog(this, types, msg); if (!this.isFinishing() && !this.isDestroyed()) { customDialog.show(); } } private void throwableView(Throwable throwable) { String message = null; if (throwable instanceof NetException) { message = throwable.getMessage() != null ? throwable.getMessage() : "接口请求失败(" + ((NetException) throwable).getCode() + ")"; } else if (throwable instanceof SocketTimeoutException) { message = "请求超时,请稍后重试"; } else if (throwable instanceof ConnectException) { message = "无法连接服务器,请检查网络"; } else if (throwable instanceof HttpException) { message = "服务器繁忙,请稍后重试"; } if (message != null) { customDialogView(2, message); } } private final Handler mCountDownHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { if (WHAT_COUNT_DOWN == msg.what) { int countDown = MAX_TIME - mCounter; if (isDestroyed()) return; if (countDown <= 0) { ChemicalApp.confs = null; ChemicalApp.subjectId = null; ChemicalApp.userData = null; callLogoutApis(success -> { ActivityUtils.startActivity(StartActivity.class); }); } else { sendEmptyMessageDelayed(WHAT_COUNT_DOWN, 1000); } mCounter++; } } }; @Override public void onUserInteraction() { mCounter = 0; } @Override protected void cdFinish() { } @Override protected void cdTime(int cd) { } @Override protected ViewBinding setViewBinding() { viewBinding = ActivityMainBinding.inflate(getLayoutInflater()); return viewBinding; } @Override protected void onInit() { getUserIds(); Handler handler = new Handler(Looper.getMainLooper()); timeUpdater = new TimeUpdater(handler, new Function1() { @Override public Unit invoke(String s) { viewBinding.inc.nowTime.setText(s); return null; } }); timeUpdater.startUpdating(); mAdapter = new CabinetAdapter(); initAdapter(); viewBinding.imgLeft.setOnClickListener(v -> { if (currentPosition > 0) { currentPosition--; recyclerView.smoothScrollToPosition(currentPosition); } }); viewBinding.imgRight.setOnClickListener(v -> { if (currentPosition < mAdapter.getItemCount() - 1) { currentPosition++; recyclerView.smoothScrollToPosition(currentPosition); } }); RelativeLayoutDebouncer.Companion.setDebouncedOnClickListener(viewBinding.inc.userLogin, 1000L, v -> { basicConfLog(); }); // 存储 viewBinding.addChemicals.setOnClickListener(v -> { //新增 if (ChemicalApp.userData != null) { if (ChemicalApp.administrators || ChemicalApp.responsibles) { planDialog = new PlanDialog(MainActivity.this, new View.OnClickListener() { @Override public void onClick(View v) { UiManager.INSTANCE.switcher(MainActivity.this, AlreadyActivity.class); planDialog.dismiss(); } }, new View.OnClickListener() { @Override public void onClick(View v) { UiManager.INSTANCE.switcher(MainActivity.this, PlanAddActivity.class); planDialog.dismiss(); } }); planDialog.show(); } else { customDialogView(2, "当前人员无权限"); } } else { basicConfLog(); } }); viewBinding.reDis.setOnClickListener(v -> { if (ChemicalApp.userData != null) { UiManager.INSTANCE.switcher(this, WasteChemicalsActivity.class); } else { basicConfLog(); } }); viewBinding.reInq.setOnClickListener(v -> { Map map = new HashMap<>(); map.put("logIn", ChemicalApp.userData != null ? 1 : 0); map.put("cabinetId", "a"); map.put("doorId", "a"); UiManager.INSTANCE.switcher(this, map, InquiryActivity.class); }); viewBinding.reCla.setOnClickListener(v -> { if (ChemicalApp.userData != null) { UiManager.INSTANCE.switcher(this, UseActivity.class); } else { basicConfLog(); } }); viewBinding.reRet.setOnClickListener(v -> { if (ChemicalApp.userData != null) { UiManager.INSTANCE.switcher(this, ChemicalsAlsoActivity.class); } else { basicConfLog(); } }); viewBinding.rlLedger.setOnClickListener(v -> { if (ChemicalApp.userData != null) { UiManager.INSTANCE.switcher(this, LedgerActivity.class); } else { basicConfLog(); } }); viewBinding.reLedger.setOnClickListener(v -> { if (ChemicalApp.userData != null) { UiManager.INSTANCE.switcher(this, ChemicalLabelingActivity.class); } else { basicConfLog(); } }); viewBinding.rlWarning.setOnClickListener(v -> { if (ChemicalApp.userData != null) { UiManager.INSTANCE.switcher(this, WarningEventsActivity.class); } else { basicConfLog(); } }); viewBinding.rlDem.setOnClickListener(v -> { UiManager.INSTANCE.switcher(this, MsdsActivity.class); }); viewBinding.inc.tvOutLogin.setOnClickListener(v -> { ChemicalApp.userData = null; ChemicalApp.subjectId = null; HttpClient.INSTANCE.setToken(null); ActivityUtils.startActivity(StartActivity.class); }); basicConf(); viewBinding.caozuoRL.setOnClickListener(v -> { viewBinding.caozuoRL.setVisibility(View.GONE); viewBinding.caozuoQrRL.setVisibility(View.VISIBLE); viewBinding.caozuoQrRL.postDelayed(() -> { viewBinding.caozuoRL.setVisibility(View.VISIBLE); viewBinding.caozuoQrRL.setVisibility(View.GONE); }, 1000 * 60); }); viewBinding.caozuoRL.post(() -> { Bitmap qrCode = CodeUtils.createQRCode( "https://labcontrol.nwafu.edu.cn/api/?type=14", 120 ); viewBinding.caozuoQr.setImageBitmap(qrCode); }); } private void callLogoutApis(LogoutCallback callback) { showLoading("退出中..."); ApiRepository.INSTANCE.loginOut().subscribe(new Consumer() { @Override public void accept(Boolean aBoolean) throws Throwable { dismissLoading(); if (callback != null) callback.onComplete(true); } }, new Consumer() { @Override public void accept(Throwable throwable) throws Throwable { dismissLoading(); if (callback != null) callback.onComplete(false); } }); } private void showTextInputDialog(String title, TextInputCallback callback) { EditText editText = new EditText(this); AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(title) .setView(editText) .setPositiveButton("确定", (dialog1, which) -> { String inputText = editText.getText().toString(); callback.onInput(inputText); }) .setNegativeButton("取消", (dialog1, which) -> { callback.onInput(null); }) .create(); dialog.show(); } interface TextInputCallback { void onInput(String input); } interface LogoutCallback { void onComplete(boolean success); } }