Fragment加动画后快速点击屏幕进行切换 产生的异常: java.lang.IllegalStateException: No host

java.lang.IllegalStateException: No host
                                                                               at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1239)
                                                                               at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1234)
                                                                               at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2046)
                                                                               at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1989)
                                                                               at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1092)
                                                                               at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                                                                               at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
                                                                               at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                                               at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
                                                                               at android.os.Handler.handleCallback(Handler.java:815)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                               at android.os.Looper.loop(Looper.java:194)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5815)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1009)

                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:804)

这是因为   正在执行动画时  手指 滑动 或者 点击屏幕中的控件 造成的

解决方法:

重写 basefragment 中的 onDetach 方法 获得 Fragment中声明的字段 然后设置字段为可进入 然后设置指定值

@Override
public void onDetach() {
    super.onDetach();
    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

每次重启项目报错1970-01-01 08:00:00.000 0-0 <no-tag> I ---------------------------- PROCESS ENDED (21062) for package com.example.kucun2 ---------------------------- 2025-06-16 02:13:56.761 22497-22497 cmd cmd E BBinder_init Processname cmd 2025-06-16 02:13:56.762 22497-22497 cmd cmd E BBinder_init hasGetProcessName cmd 2025-06-16 02:13:56.797 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.810 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684480, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.811 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684485, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.811 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684489, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.812 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684493, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.812 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684497, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.813 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684502, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.813 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684506, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.814 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684510, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.814 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684514, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.815 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684519, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.815 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684526, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.816 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684531, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.816 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684535, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.816 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684540, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.817 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684544, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.819 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684579, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.819 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684583, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.820 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684597, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.821 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684601, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.821 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684606, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.822 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684625, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.822 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684629, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.822 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684633, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.828 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684733, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.828 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684739, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.829 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684753, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.829 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684757, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.829 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684761, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.830 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684765, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.830 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684769, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.830 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684773, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.830 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684777, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.831 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684781, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.831 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684785, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.831 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684795, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.832 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684801, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.835 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684854, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.835 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684858, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.835 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684862, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.835 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684867, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.836 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.839 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.840 22500-22500 IPCThreadState service E Binder transaction failure. id: 152684962, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.841 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.842 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.847 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.850 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.850 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.852 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.853 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.856 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.860 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.869 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.870 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.877 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.881 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.895 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.900 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.907 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.909 22500-22500 Parcel service E Reading a NULL string not supported here. 2025-06-16 02:13:56.919 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686226, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.919 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686230, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.919 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686234, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.920 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686238, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.921 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686253, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.921 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686257, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.922 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686261, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.922 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686265, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.922 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686269, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.922 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686273, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.923 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686277, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.923 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686283, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.923 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686289, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.923 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686293, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.924 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686297, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.924 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686302, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.924 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686306, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.925 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686311, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.926 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686323, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.926 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686328, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.926 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686332, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.929 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686373, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.930 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686382, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.930 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686386, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.931 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686395, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.931 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686402, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.932 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686407, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.932 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686411, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.932 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686416, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.933 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686420, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.933 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686424, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.933 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686430, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.934 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686435, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.934 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686439, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.934 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686445, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.942 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686554, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.942 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686559, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.943 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686564, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.943 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686568, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.944 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686573, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.944 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686577, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.944 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686581, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.945 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686585, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.945 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686589, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.945 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686594, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.946 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686598, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.946 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686602, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.946 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686606, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.946 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686610, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.947 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686614, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.947 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686618, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.947 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686622, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.947 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686626, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.948 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686630, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.948 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686643, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.948 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686647, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.949 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686651, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.949 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686656, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.949 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686660, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.950 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686664, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.950 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686669, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.951 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686681, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.951 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686686, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.951 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686690, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.952 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686700, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.952 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686704, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.953 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686708, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.953 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686712, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.954 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686727, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.954 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686731, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.954 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686735, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.954 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686739, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.955 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686743, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.955 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686747, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.955 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686751, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.955 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686755, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.956 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686759, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.956 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686763, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.956 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686769, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.956 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686774, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.957 22500-22500 IPCThreadState service E Binder transaction failure. id: 152686779, BR_*: 29201, error: -1 (Operation not permitted) 2025-06-16 02:13:56.972 22500-22500 IPCThreadState service E Binder transaction failure. id: 152687050, BR_*: 29201, error: -1 (Operation not permitted) 1970-01-01 08:00:00.000 0-0 <no-tag> I ---------------------------- PROCESS STARTED (21838) for package com.example.kucun2 -----------package com.example.kucun2.entity.data; import static android.content.ContentValues.TAG; import android.content.Context; import android.util.Log; import com.example.kucun2.R; import com.example.kucun2.entity.Information; import com.example.kucun2.function.MyAppFnction; import com.example.kucun2.function.TLSUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; public class ApiClient { // 使用Volley、Retrofit或OkHttp实现以下方法 private static final Gson gson = new Gson(); private static OkHttpClient client; private static final String TAG = "ApiClient"; private static final String CERT_FILE = "selfsigned.crt"; // 证书文件名 // 初始化方法 public static void init(Context context) { if (client != null) return; try { // 创建信任管理器 X509TrustManager trustManager = TLSUtils.createTrustManager(context, CERT_FILE); // 创建SSL上下文 SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{trustManager}, null); // 配置OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory(), trustManager) .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .build(); Log.d(TAG, "OkHttpClient initialized with custom certificate: " + CERT_FILE); } catch (Exception e) { Log.e(TAG, "Failed to initialize secure client", e); // 回退到默认配置(生产环境不应使用) client = new OkHttpClient(); } } public static <T, R> void post(String url, Information<T> requestData, ApiCallback<R> callback) { // 1. 构建请求体(JSON格式) String jsonRequest = ReflectionJsonUtils.toJson(requestData); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonRequest); Log.d(TAG, "post: "+url); // 2. 创建POST请求 Request request = new Request.Builder() .url(url) .post(body) .build(); Log.d(TAG, "POST请求URL: " + url); Log.d(TAG, "请求数据: " + jsonRequest); // 3. 发送异步请求 client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "请求失败: " + e.getMessage()); if (callback != null) { callback.onError(-1, e.getMessage()); } } @Override public void onResponse(Call call, Response response) throws IOException { try (ResponseBody responseBody = response.body()) { if (!response.isSuccessful()) { Log.e(TAG, "服务器响应错误: " + response.code() + " - " + response.message()); if (callback != null) { callback.onError(response.code(), response.message()); } return; } // 4. 处理成功响应 String jsonResponse = responseBody.string(); Log.d(TAG, "服务器响应: " + jsonResponse); // 5. 解析为Information对象 // 注意:这里需要提前确定响应中data的类型(TypeToken) Type responseType = new TypeToken<Information<R>>() { }.getType(); Information<R> responseInfo = gson.fromJson(jsonResponse, responseType); if (callback != null) { callback.onSuccess(responseInfo); } } } }); } public static <T, R> void put(String url, Information<T> data, ApiCallback<T> callback) { String jsonRequest = ReflectionJsonUtils.toJson(data); RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonRequest); Request request = new Request.Builder() .url(url) .put(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "PUT request failed", e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful() && callback != null) { String json = response.body().string(); Type responseType = new TypeToken<Information<T>>(){}.getType(); Information<T> info = gson.fromJson(json, responseType); callback.onSuccess(info); } } }); } public static <R> void delete(String url, ApiCallback<R> callback) { Request request = new Request.Builder() .url(url) .delete() .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "DELETE request failed", e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful() && callback != null) { // 对于删除操作,通常返回空数据 callback.onSuccess(new Information<>(200, "Deleted", null)); } } }); } public static interface ApiCallback<T> { void onSuccess(Information<T> data); void onError(int statusCode, String error); } }package com.example.kucun2.entity.data; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Looper; import android.util.Log; import com.example.kucun2.entity.*; import com.example.kucun2.function.MyAppFnction; import com.example.kucun2.function.SafeLogger; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; import okhttp3.*; /** * 核心数据管理中心 * 职责: * 1. 管理所有实体类的全局存储列表 * 2. 处理网络数据载与本地持久化 * 3. 维护实体间关联关系 * 4. 管理数据同步状态 * * 优化点: * - 使用ConcurrentHashMap提升线程安全 * - 重构关联逻辑避免反射开销 * - 增强序列化/反序列化处理 * - 添详细方法级注释 */ public class Data { // ====================== 实体存储区 ====================== // 所有实体列表使用线程安全的SynchronizedList // ====================== 静态数据列表声明 ====================== public static final SynchronizedList<Bancai> bancais = new SynchronizedList<>(Bancai.class); public static final SynchronizedList<Caizhi> caizhis = new SynchronizedList<>(Caizhi.class); public static final SynchronizedList<Mupi> mupis = new SynchronizedList<>(Mupi.class); public static final SynchronizedList<Chanpin> chanpins = new SynchronizedList<>(Chanpin.class); public static final SynchronizedList<Chanpin_Zujian> chanpin_zujians = new SynchronizedList<>(Chanpin_Zujian.class); public static final SynchronizedList<Dingdan> dingdans = new SynchronizedList<>(Dingdan.class); public static final SynchronizedList<Dingdan_Chanpin> dingdan_chanpins = new SynchronizedList<>(Dingdan_Chanpin.class); public static final SynchronizedList<Dingdan_chanpin_zujian> Dingdan_chanpin_zujians = new SynchronizedList<>(Dingdan_chanpin_zujian.class); public static final SynchronizedList<Kucun> kucuns = new SynchronizedList<>(Kucun.class); public static final SynchronizedList<Zujian> zujians = new SynchronizedList<>(Zujian.class); public static final SynchronizedList<User> users = new SynchronizedList<>(User.class); public static final SynchronizedList<Jinhuo> jinhuos = new SynchronizedList<>(Jinhuo.class); private static User user; // 实体类型与列表的映射表 <实体类, 对应的同步列表> public static final Map<Class, SynchronizedList<SynchronizableEntity>> dataCollectionMap = new ConcurrentHashMap<>();; private static final Gson gson = GsonFactory.createGson(); private static OkHttpClient client; private static final String TAG = "DataLoader"; // 静态初始化:建立实体类型与列表的映射关系 static { try { // 通过反射获取所有SynchronizedList字段 for (Field field : Data.class.getDeclaredFields()) { if (SynchronizedList.class.equals(field.getType())) { SynchronizedList<?> list = (SynchronizedList<?>) field.get(null); if (list != null) { // 将实体类型与列表关联 dataCollectionMap.put(list.getEntityType(), (SynchronizedList<SynchronizableEntity>) list); } } } } catch (IllegalAccessException e) { throw new RuntimeException("初始化dataCollectionMap失败", e); } } // ====================== 核心数据载方法 ====================== /** * 从服务器载全量数据 * @param context Android上下文 * @param callback 载结果回调 */ public static void loadAllData(Context context, LoadDataCallback callback) { // 主线程检查 if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException("必须在主线程调用Data.loadAllData"); } ensurePreservedObjects(); // 确保存在预置对象 // 使用传入的 Context 获取主线程 Handler Handler mainHandler = new Handler(context.getMainLooper()); // 确保使用安全的客户端 if (client == null) { client = MyAppFnction.getClient(); } ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(() -> { SynchronizableEntity.setSyncEnabled(false); String url = MyAppFnction.getStringResource("string", "url") + MyAppFnction.getStringResource("string", "url_all"); Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "Failed to load data", e); SynchronizableEntity.setSyncEnabled(true); mainHandler.post(() -> { if (callback != null) callback.onFailure(); }); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { Log.e(TAG, "Unexpected response code: " + response.code()); SynchronizableEntity.setSyncEnabled(true); mainHandler.post(() -> { if (callback != null) callback.onFailure(); }); return; } String responseData = response.body().string(); SynchronizableEntity.setSyncEnabled(true); ensurePreservedObjects(); // 在主线程处理解析 mainHandler.post(() -> { parseAndAssignData(responseData, context, callback); }); } }); }); } // ====================== 数据处理私有方法 ====================== /** * 解析JSON数据并更新到实体列表 */ private static void parseAndAssignData(String jsonData, Context context, LoadDataCallback callback) { try { // 解析顶层响应结构 Type responseType = new TypeToken<Information<AllDataResponse>>() {}.getType(); Information<AllDataResponse> info = gson.fromJson(jsonData, responseType); Log.d(TAG, "parseAndAssignData: "+jsonData); // 验证响应有效性 if (info == null || info.getData() == null || info.getStatus() != 200) { throw new IllegalStateException("无效服务器响应"); } AllDataResponse allData = info.getData(); SafeLogger.d("data", "原始数据: " + gson.toJson(allData)); // 更新所有数据列表 updateAllLists(allData); automaticAssociation(); // 建立实体关联 setAllEntitiesState(SynchronizableEntity.SyncState.MODIFIED); // 设置状态 safeCallback(callback, true); // 成功回调 } catch (Exception e) { Log.e(TAG, "数据处理异常: " + e.getMessage()); safeCallback(callback, false); } finally { SynchronizableEntity.setSyncEnabled(true); // 重新启用同步 } } /** * 批量更新所有实体列表 */ private static void updateAllLists(AllDataResponse allData) { updateList(bancais, allData.bancais); updateList(caizhis, allData.caizhis); updateList(mupis, allData.mupis); updateList(chanpins, allData.chanpins); updateList(chanpin_zujians, allData.chanpin_zujians); updateList(dingdans, allData.dingdans); updateList(dingdan_chanpins, allData.dingdan_chanpins); updateList(Dingdan_chanpin_zujians, allData.Dingdan_chanpin_zujians); updateList(kucuns, allData.kucuns); updateList(zujians, allData.zujians); updateList(users, allData.users); updateList(jinhuos, allData.jinhuos); } /** * 安全更新单个列表(保留预置对象) */ private static <T extends SynchronizableEntity> void updateList( List<T> existingList, List<T> newList ) { if (newList == null) return; // 保留现有列表中的预置对象 List<T> preservedItems = existingList.stream() .filter(item -> item != null && item.isPreservedObject()) .collect(Collectors.toList()); // 清空后重新添(预置对象 + 有效新数据) existingList.clear(); existingList.addAll(preservedItems); existingList.addAll(newList.stream() .filter(item -> item != null && item.getId() != null && item.getId() != -1) .collect(Collectors.toList()) ); } /** * 确保每个列表都有预置对象(用于表示空值/默认值) */ private static void ensurePreservedObjects() { // 为每个实体类型检查并添预置对象 addIfMissing(bancais, Bancai.class); addIfMissing(caizhis, Caizhi.class); addIfMissing(mupis, Mupi.class); addIfMissing(chanpins, Chanpin.class); addIfMissing(chanpin_zujians, Chanpin_Zujian.class); addIfMissing(dingdans, Dingdan.class); addIfMissing(kucuns, Kucun.class); addIfMissing(zujians, Zujian.class); addIfMissing(Dingdan_chanpin_zujians, Dingdan_chanpin_zujian.class); addIfMissing(dingdan_chanpins, Dingdan_Chanpin.class); addIfMissing(jinhuos, Jinhuo.class); addIfMissing(users, User.class); } private static <T extends SynchronizableEntity> void addIfMissing( List<T> list, Class<T> clazz ) { if (!containsPreservedObject(list)) { list.add(createInstance(clazz)); } } /** * 检查列表是否包含预置对象 * * @param list 目标实体列表 * @return 是否包含预置对象 */ private static <T extends SynchronizableEntity> boolean containsPreservedObject(List<T> list) { return list.stream().anyMatch(item -> item != null && item.isPreservedObject() ); } /** * 自动建立实体间关联关系(通过反射实现) */ private static void automaticAssociation() { for (Class<?> entityClass : dataCollectionMap.keySet()) { try { associateEntities(dataCollectionMap.get(entityClass)); } catch (Exception e) { Log.e(TAG, entityClass.getSimpleName() + " 关联失败", e); } } } private static <T extends SynchronizableEntity> void associateEntities( SynchronizedList<T> list ) throws IllegalAccessException, ClassNotFoundException { for (T entity : list) { if (entity == null) continue; for (Field field : entity.getClass().getDeclaredFields()) { field.setAccessible(true); Class<?> fieldType = field.getType(); // 处理实体引用字段 if (SynchronizableEntity.class.isAssignableFrom(fieldType)) { associateSingleReference(entity, field); } // 处理实体列表字段 else if (List.class.isAssignableFrom(fieldType)) { associateReferenceList(entity, field); } // 处理基础类型字段 else { setDefaultPrimitiveValue(entity, field); } } } } // ====================== 关联辅助方法 ====================== private static void associateSingleReference( SynchronizableEntity entity, Field field ) throws IllegalAccessException { SynchronizableEntity ref = (SynchronizableEntity) field.get(entity); Class<?> targetType = field.getType(); // 查找目标实体 SynchronizableEntity target = findTargetEntity(ref, targetType); field.set(entity, target); } private static void associateReferenceList( SynchronizableEntity entity, Field field ) throws IllegalAccessException, ClassNotFoundException { // 获取列表泛型类型 Type genericType = field.getGenericType(); if (!(genericType instanceof ParameterizedType)) return; Class<?> itemType = Class.forName( ((ParameterizedType) genericType).getActualTypeArguments()[0].getTypeName() ); // 只处理实体列表 if (!SynchronizableEntity.class.isAssignableFrom(itemType)) return; List<SynchronizableEntity> refList = (List<SynchronizableEntity>) field.get(entity); if (refList == null) { refList = new ArrayList<>(); field.set(entity, refList); } // 清理空值并重建引用 refList.removeAll(Collections.singleton(null)); for (int i = 0; i < refList.size(); i++) { refList.set(i, findTargetEntity(refList.get(i), itemType)); } } /** * 查找关联实体(优先匹配ID,找不到则使用预置对象) */ private static SynchronizableEntity findTargetEntity( SynchronizableEntity ref, Class<?> targetType ) { SynchronizedList<SynchronizableEntity> targetList = dataCollectionMap.get(targetType); if (targetList == null) return null; // 无效引用时返回预置对象 if (ref == null || ref.getId() == null || ref.getId() < 0) { return targetList.stream() .filter(SynchronizableEntity::isPreservedObject) .findFirst().orElse(null); } // 按ID查找目标实体 return targetList.stream() .filter(e -> ref.getId().equals(e.getId())) .findFirst() .orElseGet(() -> targetList.stream() // 找不到时回退到预置对象 .filter(SynchronizableEntity::isPreservedObject) .findFirst().orElse(null) ); } // ====================== 工具方法 ====================== /** * 创建带默认值的实体实例(用作预置对象) */ public static <T> T createInstance(Class<T> clazz) { try { T instance = clazz.getDeclaredConstructor().newInstance(); // 设置基础字段默认值 for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); setDefaultFieldValue(instance, field); } // 设置特殊字段 clazz.getMethod("setId", Integer.class).invoke(instance, -1); clazz.getMethod("setState", SynchronizableEntity.SyncState.class) .invoke(instance, SynchronizableEntity.SyncState.PRESERVED); return instance; } catch (Exception e) { Log.e("Data", "创建实例失败: " + clazz.getName(), e); try { return clazz.newInstance(); // 回退创建 } catch (Exception ex) { throw new RuntimeException("无法创建实例", ex); } } } private static <T> void setDefaultFieldValue(T instance, Field field) throws IllegalAccessException { Class<?> type = field.getType(); if (type == String.class) field.set(instance, "无"); else if (type == Integer.class || type == int.class) field.set(instance, -1); else if (type == Double.class || type == double.class) field.set(instance, -1.0); else if (type == Boolean.class || type == boolean.class) field.set(instance, false); else if (type == Date.class) field.set(instance, new Date()); else if (SynchronizableEntity.class.isAssignableFrom(type)) { field.set(instance, getPreservedEntity((Class<?>) type)); } else if (List.class.isAssignableFrom(type)) { field.set(instance, new ArrayList<>()); } } private static SynchronizableEntity getPreservedEntity(Class<?> type) { return dataCollectionMap.get(type).stream() .filter(SynchronizableEntity::isPreservedObject) .findFirst().orElse(null); } private static void setDefaultPrimitiveValue( SynchronizableEntity entity, Field field ) throws IllegalAccessException { if (field.get(entity) != null) return; Class<?> type = field.getType(); if (type == String.class) field.set(entity, "无"); else if (type == Integer.class || type == int.class) field.set(entity, -1); else if (type == Double.class || type == double.class) field.set(entity, -1.0); else if (type == Boolean.class || type == boolean.class) field.set(entity, false); else if (type == Date.class) field.set(entity, new Date()); } /** * 主线程安全回调 */ private static void safeCallback(LoadDataCallback callback, boolean success) { new Handler(Looper.getMainLooper()).post(() -> { if (callback == null) return; if (success) callback.onSuccess(); else callback.onFailure(); }); } /** * 设置所有实体同步状态 */ private static void setAllEntitiesState(SynchronizableEntity.SyncState state) { dataCollectionMap.values().forEach(list -> list.forEach(entity -> { if (entity != null) entity.setState(state); }) ); } public static String exportToJson() { ExportData exportData = new ExportData(); exportData.bancais = new ArrayList<>(bancais); exportData.caizhis = new ArrayList<>(caizhis); // 初始化其他列表... Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(SynchronizableEntity.class, new EntitySerializer()) .create(); return gson.toJson(exportData); } public static void importFromJson(String json, Context context) { Gson gson = new GsonBuilder() .registerTypeAdapter(SynchronizableEntity.class, new EntityDeserializer()) .create(); Type exportType = new TypeToken<ExportData>(){}.getType(); ExportData importData = gson.fromJson(json, exportType); // 更新数据列表 updateList(bancais, importData.bancais); updateList(caizhis, importData.caizhis); // 更新其他列表... automaticAssociation(); setAllEntitiesState(SynchronizableEntity.SyncState.MODIFIED); // 保存到SharedPreferences saveToPreferences(context, json); } private static void saveToPreferences(Context context, String json) { SharedPreferences prefs = context.getSharedPreferences("DataStore", Context.MODE_PRIVATE); prefs.edit().putString("jsonData", json).apply(); } public static void loadFromPreferences(Context context) { SharedPreferences prefs = context.getSharedPreferences("DataStore", Context.MODE_PRIVATE); String json = prefs.getString("jsonData", null); if (json != null) { importFromJson(json, context); } } // ====================== 内部类/接口 ====================== public interface LoadDataCallback { void onSuccess(); void onFailure(); } /** JSON响应数据结构 */ public static class AllDataResponse { public List<Bancai> bancais; public List<Caizhi> caizhis; public List<Mupi> mupis; public List<Chanpin> chanpins; public List<Chanpin_Zujian> chanpin_zujians; public List<Dingdan> dingdans; public List<Dingdan_Chanpin> dingdan_chanpins; public List<Dingdan_chanpin_zujian> Dingdan_chanpin_zujians; public List<Kucun> kucuns; public List<Zujian> zujians; public List<User> users; public List<Jinhuo> jinhuos; } // 在Data.java中添 public static class ExportData { public List<Bancai> bancais; public List<Caizhi> caizhis; public List<Mupi> mupis; public List<Chanpin> chanpins; public List<Chanpin_Zujian> chanpin_zujians; public List<Dingdan> dingdans; public List<Dingdan_Chanpin> dingdan_chanpins; public List<Dingdan_chanpin_zujian> Dingdan_chanpin_zujians; public List<Kucun> kucuns; public List<Zujian> zujians; public List<User> users; public List<Jinhuo> jinhuos; } private static class EntityDeserializer implements JsonDeserializer<SynchronizableEntity> { @Override public SynchronizableEntity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = json.getAsJsonObject(); String entityType = obj.get("entityType").getAsString(); Integer id = obj.get("id").getAsInt(); // 创建临时实体(只包含ID) try { Class<?> clazz = Class.forName("com.example.kucun2.entity." + entityType); SynchronizableEntity entity = (SynchronizableEntity) clazz.newInstance(); entity.setId(id); return entity; } catch (Exception e) { return null; } } } private static class EntitySerializer implements JsonSerializer<SynchronizableEntity> { @Override public JsonElement serialize(SynchronizableEntity src, Type typeOfSrc, JsonSerializationContext context) { JsonObject obj = new JsonObject(); obj.addProperty("id", src.getId()); obj.addProperty("entityType", src.getClass().getSimpleName()); return obj; } } }package com.example.kucun2; import android.os.Bundle; import android.os.Looper; import android.view.View; import android.view.Menu; import com.example.kucun2.entity.data.ApiClient; import com.example.kucun2.entity.data.Data; import com.google.android.material.snackbar.Snackbar; import com.google.android.material.navigation.NavigationView; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.AppCompatActivity; import com.example.kucun2.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { private AppBarConfiguration mAppBarConfiguration; private ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 启动数据载 loadAppData(); } private void initUI() { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException("Must be called on the main thread"); } ApiClient.init(this); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // ... 其他初始化代码 ... setSupportActionBar(binding.appBarMain.toolbar); binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null) .setAnchorView(R.id.fab).show(); } }); DrawerLayout drawer = binding.drawerLayout; NavigationView navigationView = binding.navView; // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. mAppBarConfiguration = new AppBarConfiguration.Builder( R.id.nav_home, R.id.nav_kucun, R.id.nav_add_jinhuo, R.id.nav_diandan) .setOpenableLayout(drawer) .build(); NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main); NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration); NavigationUI.setupWithNavController(navigationView, navController); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onSupportNavigateUp() { NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main); return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp(); } public interface OnDataLoadListener { void onDataLoaded(); void onDataError(); } private OnDataLoadListener dataLoadListener; public void setOnDataLoadListener(OnDataLoadListener listener) { this.dataLoadListener = listener; } private void loadAppData() { Data.loadAllData(getApplicationContext(), new Data.LoadDataCallback() { @Override public void onSuccess() { runOnUiThread(() -> { if (dataLoadListener != null) { runOnUiThread(dataLoadListener::onDataLoaded); } initUI(); }); } @Override public void onFailure() { runOnUiThread(() -> { if (dataLoadListener != null) { runOnUiThread(dataLoadListener::onDataError); } }); } }); } }
06-17
E 鍒涘缓淇′换绠$悊鍣ㄥけ璐� java.io.FileNotFoundException: server_cert.crt at android.content.res.AssetManager.nativeOpenAsset(Native Method) at android.content.res.AssetManager.open(AssetManager.java:1133) at android.content.res.AssetManager.open(AssetManager.java:1110) at com.example.kucun2.function.TLSUtils.loadCertificate(TLSUtils.java:105) at com.example.kucun2.function.TLSUtils.createTrustManager(TLSUtils.java:55) at com.example.kucun2.entity.data.ApiClient.init(ApiClient.java:47) at com.example.kucun2.MainActivity.initUI(MainActivity.java:40) at com.example.kucun2.MainActivity.-$$Nest$minitUI(Unknown Source:0) at com.example.kucun2.MainActivity$2.lambda$onSuccess$0(MainActivity.java:107) at com.example.kucun2.MainActivity$2.$r8$lambda$H663lyBU3DFFRVSp8j3jjHI0xzg(Unknown Source:0) at com.example.kucun2.MainActivity$2$$ExternalSyntheticLambda1.run(D8$$SyntheticClass:0) at android.app.Activity.runOnUiThread(Activity.java:8377) at com.example.kucun2.MainActivity$2.onSuccess(MainActivity.java:103) at com.example.kucun2.entity.data.Data.lambda$safeCallback$6(Data.java:444) at com.example.kucun2.entity.data.Data$$ExternalSyntheticLambda2.run(D8$$SyntheticClass:0) at android.os.Handler.handleCallback(Handler.java:1014) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loopOnce(Looper.java:250) at android.os.Looper.loop(Looper.java:340) at android.app.ActivityThread.main(ActivityThread.java:9913) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:621) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:957) 2025-06-16 02:05:49.168 19164-19164 ApiClient com.example.kucun2 D OkHttpClient initialized with custom certificate: server_cert.crtpackage com.example.kucun2.entity.data; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Looper; import android.util.Log; import com.example.kucun2.entity.*; import com.example.kucun2.function.MyAppFnction; import com.example.kucun2.function.SafeLogger; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; import okhttp3.*; /** * 核心数据管理中心 * 职责: * 1. 管理所有实体类的全局存储列表 * 2. 处理网络数据载与本地持久化 * 3. 维护实体间关联关系 * 4. 管理数据同步状态 * * 优化点: * - 使用ConcurrentHashMap提升线程安全 * - 重构关联逻辑避免反射开销 * - 增强序列化/反序列化处理 * - 添详细方法级注释 */ public class Data { // ====================== 实体存储区 ====================== // 所有实体列表使用线程安全的SynchronizedList // ====================== 静态数据列表声明 ====================== public static final SynchronizedList<Bancai> bancais = new SynchronizedList<>(Bancai.class); public static final SynchronizedList<Caizhi> caizhis = new SynchronizedList<>(Caizhi.class); public static final SynchronizedList<Mupi> mupis = new SynchronizedList<>(Mupi.class); public static final SynchronizedList<Chanpin> chanpins = new SynchronizedList<>(Chanpin.class); public static final SynchronizedList<Chanpin_Zujian> chanpin_zujians = new SynchronizedList<>(Chanpin_Zujian.class); public static final SynchronizedList<Dingdan> dingdans = new SynchronizedList<>(Dingdan.class); public static final SynchronizedList<Dingdan_Chanpin> dingdan_chanpins = new SynchronizedList<>(Dingdan_Chanpin.class); public static final SynchronizedList<Dingdan_chanpin_zujian> Dingdan_chanpin_zujians = new SynchronizedList<>(Dingdan_chanpin_zujian.class); public static final SynchronizedList<Kucun> kucuns = new SynchronizedList<>(Kucun.class); public static final SynchronizedList<Zujian> zujians = new SynchronizedList<>(Zujian.class); public static final SynchronizedList<User> users = new SynchronizedList<>(User.class); public static final SynchronizedList<Jinhuo> jinhuos = new SynchronizedList<>(Jinhuo.class); private static User user; // 实体类型与列表的映射表 <实体类, 对应的同步列表> public static final Map<Class, SynchronizedList<SynchronizableEntity>> dataCollectionMap = new ConcurrentHashMap<>();; private static final Gson gson = GsonFactory.createGson(); private static OkHttpClient client; private static final String TAG = "DataLoader"; // 静态初始化:建立实体类型与列表的映射关系 static { try { // 通过反射获取所有SynchronizedList字段 for (Field field : Data.class.getDeclaredFields()) { if (SynchronizedList.class.equals(field.getType())) { SynchronizedList<?> list = (SynchronizedList<?>) field.get(null); if (list != null) { // 将实体类型与列表关联 dataCollectionMap.put(list.getEntityType(), (SynchronizedList<SynchronizableEntity>) list); } } } } catch (IllegalAccessException e) { throw new RuntimeException("初始化dataCollectionMap失败", e); } } // ====================== 核心数据载方法 ====================== /** * 从服务器载全量数据 * @param context Android上下文 * @param callback 载结果回调 */ public static void loadAllData(Context context, LoadDataCallback callback) { // 主线程检查 if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException("必须在主线程调用Data.loadAllData"); } ensurePreservedObjects(); // 确保存在预置对象 // 使用传入的 Context 获取主线程 Handler Handler mainHandler = new Handler(context.getMainLooper()); // 确保使用安全的客户端 if (client == null) { client = MyAppFnction.getClient(); } ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(() -> { SynchronizableEntity.setSyncEnabled(false); String url = MyAppFnction.getStringResource("string", "url") + MyAppFnction.getStringResource("string", "url_all"); Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "Failed to load data", e); SynchronizableEntity.setSyncEnabled(true); mainHandler.post(() -> { if (callback != null) callback.onFailure(); }); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { Log.e(TAG, "Unexpected response code: " + response.code()); SynchronizableEntity.setSyncEnabled(true); mainHandler.post(() -> { if (callback != null) callback.onFailure(); }); return; } String responseData = response.body().string(); SynchronizableEntity.setSyncEnabled(true); ensurePreservedObjects(); // 在主线程处理解析 mainHandler.post(() -> { parseAndAssignData(responseData, context, callback); }); } }); }); } // ====================== 数据处理私有方法 ====================== /** * 解析JSON数据并更新到实体列表 */ private static void parseAndAssignData(String jsonData, Context context, LoadDataCallback callback) { try { // 解析顶层响应结构 Type responseType = new TypeToken<Information<AllDataResponse>>() {}.getType(); Information<AllDataResponse> info = gson.fromJson(jsonData, responseType); Log.d(TAG, "parseAndAssignData: "+jsonData); // 验证响应有效性 if (info == null || info.getData() == null || info.getStatus() != 200) { throw new IllegalStateException("无效服务器响应"); } AllDataResponse allData = info.getData(); SafeLogger.d("data", "原始数据: " + gson.toJson(allData)); // 更新所有数据列表 updateAllLists(allData); automaticAssociation(); // 建立实体关联 setAllEntitiesState(SynchronizableEntity.SyncState.MODIFIED); // 设置状态 safeCallback(callback, true); // 成功回调 } catch (Exception e) { Log.e(TAG, "数据处理异常: " + e.getMessage()); safeCallback(callback, false); } finally { SynchronizableEntity.setSyncEnabled(true); // 重新启用同步 } } /** * 批量更新所有实体列表 */ private static void updateAllLists(AllDataResponse allData) { updateList(bancais, allData.bancais); updateList(caizhis, allData.caizhis); updateList(mupis, allData.mupis); updateList(chanpins, allData.chanpins); updateList(chanpin_zujians, allData.chanpin_zujians); updateList(dingdans, allData.dingdans); updateList(dingdan_chanpins, allData.dingdan_chanpins); updateList(Dingdan_chanpin_zujians, allData.Dingdan_chanpin_zujians); updateList(kucuns, allData.kucuns); updateList(zujians, allData.zujians); updateList(users, allData.users); updateList(jinhuos, allData.jinhuos); } /** * 安全更新单个列表(保留预置对象) */ private static <T extends SynchronizableEntity> void updateList( List<T> existingList, List<T> newList ) { if (newList == null) return; // 保留现有列表中的预置对象 List<T> preservedItems = existingList.stream() .filter(item -> item != null && item.isPreservedObject()) .collect(Collectors.toList()); // 清空后重新添(预置对象 + 有效新数据) existingList.clear(); existingList.addAll(preservedItems); existingList.addAll(newList.stream() .filter(item -> item != null && item.getId() != null && item.getId() != -1) .collect(Collectors.toList()) ); } /** * 确保每个列表都有预置对象(用于表示空值/默认值) */ private static void ensurePreservedObjects() { // 为每个实体类型检查并添预置对象 addIfMissing(bancais, Bancai.class); addIfMissing(caizhis, Caizhi.class); addIfMissing(mupis, Mupi.class); addIfMissing(chanpins, Chanpin.class); addIfMissing(chanpin_zujians, Chanpin_Zujian.class); addIfMissing(dingdans, Dingdan.class); addIfMissing(kucuns, Kucun.class); addIfMissing(zujians, Zujian.class); addIfMissing(Dingdan_chanpin_zujians, Dingdan_chanpin_zujian.class); addIfMissing(dingdan_chanpins, Dingdan_Chanpin.class); addIfMissing(jinhuos, Jinhuo.class); addIfMissing(users, User.class); } private static <T extends SynchronizableEntity> void addIfMissing( List<T> list, Class<T> clazz ) { if (!containsPreservedObject(list)) { list.add(createInstance(clazz)); } } /** * 检查列表是否包含预置对象 * * @param list 目标实体列表 * @return 是否包含预置对象 */ private static <T extends SynchronizableEntity> boolean containsPreservedObject(List<T> list) { return list.stream().anyMatch(item -> item != null && item.isPreservedObject() ); } /** * 自动建立实体间关联关系(通过反射实现) */ private static void automaticAssociation() { for (Class<?> entityClass : dataCollectionMap.keySet()) { try { associateEntities(dataCollectionMap.get(entityClass)); } catch (Exception e) { Log.e(TAG, entityClass.getSimpleName() + " 关联失败", e); } } } private static <T extends SynchronizableEntity> void associateEntities( SynchronizedList<T> list ) throws IllegalAccessException, ClassNotFoundException { for (T entity : list) { if (entity == null) continue; for (Field field : entity.getClass().getDeclaredFields()) { field.setAccessible(true); Class<?> fieldType = field.getType(); // 处理实体引用字段 if (SynchronizableEntity.class.isAssignableFrom(fieldType)) { associateSingleReference(entity, field); } // 处理实体列表字段 else if (List.class.isAssignableFrom(fieldType)) { associateReferenceList(entity, field); } // 处理基础类型字段 else { setDefaultPrimitiveValue(entity, field); } } } } // ====================== 关联辅助方法 ====================== private static void associateSingleReference( SynchronizableEntity entity, Field field ) throws IllegalAccessException { SynchronizableEntity ref = (SynchronizableEntity) field.get(entity); Class<?> targetType = field.getType(); // 查找目标实体 SynchronizableEntity target = findTargetEntity(ref, targetType); field.set(entity, target); } private static void associateReferenceList( SynchronizableEntity entity, Field field ) throws IllegalAccessException, ClassNotFoundException { // 获取列表泛型类型 Type genericType = field.getGenericType(); if (!(genericType instanceof ParameterizedType)) return; Class<?> itemType = Class.forName( ((ParameterizedType) genericType).getActualTypeArguments()[0].getTypeName() ); // 只处理实体列表 if (!SynchronizableEntity.class.isAssignableFrom(itemType)) return; List<SynchronizableEntity> refList = (List<SynchronizableEntity>) field.get(entity); if (refList == null) { refList = new ArrayList<>(); field.set(entity, refList); } // 清理空值并重建引用 refList.removeAll(Collections.singleton(null)); for (int i = 0; i < refList.size(); i++) { refList.set(i, findTargetEntity(refList.get(i), itemType)); } } /** * 查找关联实体(优先匹配ID,找不到则使用预置对象) */ private static SynchronizableEntity findTargetEntity( SynchronizableEntity ref, Class<?> targetType ) { SynchronizedList<SynchronizableEntity> targetList = dataCollectionMap.get(targetType); if (targetList == null) return null; // 无效引用时返回预置对象 if (ref == null || ref.getId() == null || ref.getId() < 0) { return targetList.stream() .filter(SynchronizableEntity::isPreservedObject) .findFirst().orElse(null); } // 按ID查找目标实体 return targetList.stream() .filter(e -> ref.getId().equals(e.getId())) .findFirst() .orElseGet(() -> targetList.stream() // 找不到时回退到预置对象 .filter(SynchronizableEntity::isPreservedObject) .findFirst().orElse(null) ); } // ====================== 工具方法 ====================== /** * 创建带默认值的实体实例(用作预置对象) */ public static <T> T createInstance(Class<T> clazz) { try { T instance = clazz.getDeclaredConstructor().newInstance(); // 设置基础字段默认值 for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); setDefaultFieldValue(instance, field); } // 设置特殊字段 clazz.getMethod("setId", Integer.class).invoke(instance, -1); clazz.getMethod("setState", SynchronizableEntity.SyncState.class) .invoke(instance, SynchronizableEntity.SyncState.PRESERVED); return instance; } catch (Exception e) { Log.e("Data", "创建实例失败: " + clazz.getName(), e); try { return clazz.newInstance(); // 回退创建 } catch (Exception ex) { throw new RuntimeException("无法创建实例", ex); } } } private static <T> void setDefaultFieldValue(T instance, Field field) throws IllegalAccessException { Class<?> type = field.getType(); if (type == String.class) field.set(instance, "无"); else if (type == Integer.class || type == int.class) field.set(instance, -1); else if (type == Double.class || type == double.class) field.set(instance, -1.0); else if (type == Boolean.class || type == boolean.class) field.set(instance, false); else if (type == Date.class) field.set(instance, new Date()); else if (SynchronizableEntity.class.isAssignableFrom(type)) { field.set(instance, getPreservedEntity((Class<?>) type)); } else if (List.class.isAssignableFrom(type)) { field.set(instance, new ArrayList<>()); } } private static SynchronizableEntity getPreservedEntity(Class<?> type) { return dataCollectionMap.get(type).stream() .filter(SynchronizableEntity::isPreservedObject) .findFirst().orElse(null); } private static void setDefaultPrimitiveValue( SynchronizableEntity entity, Field field ) throws IllegalAccessException { if (field.get(entity) != null) return; Class<?> type = field.getType(); if (type == String.class) field.set(entity, "无"); else if (type == Integer.class || type == int.class) field.set(entity, -1); else if (type == Double.class || type == double.class) field.set(entity, -1.0); else if (type == Boolean.class || type == boolean.class) field.set(entity, false); else if (type == Date.class) field.set(entity, new Date()); } /** * 主线程安全回调 */ private static void safeCallback(LoadDataCallback callback, boolean success) { new Handler(Looper.getMainLooper()).post(() -> { if (callback == null) return; if (success) callback.onSuccess(); else callback.onFailure(); }); } /** * 设置所有实体同步状态 */ private static void setAllEntitiesState(SynchronizableEntity.SyncState state) { dataCollectionMap.values().forEach(list -> list.forEach(entity -> { if (entity != null) entity.setState(state); }) ); } public static String exportToJson() { ExportData exportData = new ExportData(); exportData.bancais = new ArrayList<>(bancais); exportData.caizhis = new ArrayList<>(caizhis); // 初始化其他列表... Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(SynchronizableEntity.class, new EntitySerializer()) .create(); return gson.toJson(exportData); } public static void importFromJson(String json, Context context) { Gson gson = new GsonBuilder() .registerTypeAdapter(SynchronizableEntity.class, new EntityDeserializer()) .create(); Type exportType = new TypeToken<ExportData>(){}.getType(); ExportData importData = gson.fromJson(json, exportType); // 更新数据列表 updateList(bancais, importData.bancais); updateList(caizhis, importData.caizhis); // 更新其他列表... automaticAssociation(); setAllEntitiesState(SynchronizableEntity.SyncState.MODIFIED); // 保存到SharedPreferences saveToPreferences(context, json); } private static void saveToPreferences(Context context, String json) { SharedPreferences prefs = context.getSharedPreferences("DataStore", Context.MODE_PRIVATE); prefs.edit().putString("jsonData", json).apply(); } public static void loadFromPreferences(Context context) { SharedPreferences prefs = context.getSharedPreferences("DataStore", Context.MODE_PRIVATE); String json = prefs.getString("jsonData", null); if (json != null) { importFromJson(json, context); } } // ====================== 内部类/接口 ====================== public interface LoadDataCallback { void onSuccess(); void onFailure(); } /** JSON响应数据结构 */ public static class AllDataResponse { public List<Bancai> bancais; public List<Caizhi> caizhis; public List<Mupi> mupis; public List<Chanpin> chanpins; public List<Chanpin_Zujian> chanpin_zujians; public List<Dingdan> dingdans; public List<Dingdan_Chanpin> dingdan_chanpins; public List<Dingdan_chanpin_zujian> Dingdan_chanpin_zujians; public List<Kucun> kucuns; public List<Zujian> zujians; public List<User> users; public List<Jinhuo> jinhuos; } // 在Data.java中添 public static class ExportData { public List<Bancai> bancais; public List<Caizhi> caizhis; public List<Mupi> mupis; public List<Chanpin> chanpins; public List<Chanpin_Zujian> chanpin_zujians; public List<Dingdan> dingdans; public List<Dingdan_Chanpin> dingdan_chanpins; public List<Dingdan_chanpin_zujian> Dingdan_chanpin_zujians; public List<Kucun> kucuns; public List<Zujian> zujians; public List<User> users; public List<Jinhuo> jinhuos; } private static class EntityDeserializer implements JsonDeserializer<SynchronizableEntity> { @Override public SynchronizableEntity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = json.getAsJsonObject(); String entityType = obj.get("entityType").getAsString(); Integer id = obj.get("id").getAsInt(); // 创建临时实体(只包含ID) try { Class<?> clazz = Class.forName("com.example.kucun2.entity." + entityType); SynchronizableEntity entity = (SynchronizableEntity) clazz.newInstance(); entity.setId(id); return entity; } catch (Exception e) { return null; } } } private static class EntitySerializer implements JsonSerializer<SynchronizableEntity> { @Override public JsonElement serialize(SynchronizableEntity src, Type typeOfSrc, JsonSerializationContext context) { JsonObject obj = new JsonObject(); obj.addProperty("id", src.getId()); obj.addProperty("entityType", src.getClass().getSimpleName()); return obj; } } }package com.example.kucun2; import android.os.Bundle; import android.os.Looper; import android.view.View; import android.view.Menu; import com.example.kucun2.entity.data.ApiClient; import com.example.kucun2.entity.data.Data; import com.google.android.material.snackbar.Snackbar; import com.google.android.material.navigation.NavigationView; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.AppCompatActivity; import com.example.kucun2.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { private AppBarConfiguration mAppBarConfiguration; private ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 启动数据载 loadAppData(); } private void initUI() { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException("Must be called on the main thread"); } ApiClient.init(this); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // ... 其他初始化代码 ... setSupportActionBar(binding.appBarMain.toolbar); binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null) .setAnchorView(R.id.fab).show(); } }); DrawerLayout drawer = binding.drawerLayout; NavigationView navigationView = binding.navView; // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. mAppBarConfiguration = new AppBarConfiguration.Builder( R.id.nav_home, R.id.nav_kucun, R.id.nav_add_jinhuo, R.id.nav_diandan) .setOpenableLayout(drawer) .build(); NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main); NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration); NavigationUI.setupWithNavController(navigationView, navController); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onSupportNavigateUp() { NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main); return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp(); } public interface OnDataLoadListener { void onDataLoaded(); void onDataError(); } private OnDataLoadListener dataLoadListener; public void setOnDataLoadListener(OnDataLoadListener listener) { this.dataLoadListener = listener; } private void loadAppData() { Data.loadAllData(getApplicationContext(), new Data.LoadDataCallback() { @Override public void onSuccess() { runOnUiThread(() -> { if (dataLoadListener != null) { runOnUiThread(dataLoadListener::onDataLoaded); } initUI(); }); } @Override public void onFailure() { runOnUiThread(() -> { if (dataLoadListener != null) { runOnUiThread(dataLoadListener::onDataError); } }); } }); } }package com.example.kucun2.function; import android.content.Context; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.Arrays; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; public class TLSUtils { private static final String TAG = "TLSUtils"; /** * 创建信任自签名证书的SSL上下文 */ public static SSLContext createSSLContext(Context context, String fileName) { try { X509TrustManager trustManager = createTrustManager(context, fileName); return createSSLContext(trustManager); } catch (Exception e) { Log.e(TAG, "创建SSL上下文失败", e); return null; } } /** * 使用信任管理器创建SSL上下文 */ public static SSLContext createSSLContext(X509TrustManager trustManager) throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{trustManager}, null); return sslContext; } /** * 创建信任管理器 */ public static X509TrustManager createTrustManager(Context context, String fileName) { try { // 载证书 Certificate certificate = loadCertificate(context, fileName); // 创建包含证书的KeyStore KeyStore keyStore = createKeyStoreWithCertificate(certificate); // 初始化信任管理器工厂 TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); // 查找X509TrustManager for (TrustManager tm : tmf.getTrustManagers()) { if (tm instanceof X509TrustManager) { return (X509TrustManager) tm; } } throw new RuntimeException("未找到X509TrustManager"); } catch (Exception e) { Log.e(TAG, "创建信任管理器失败", e); return getSystemDefaultTrustManager(); // 回退到系统默认 } } /** * 获取系统默认信任管理器 */ private static X509TrustManager getSystemDefaultTrustManager() { try { TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); // 初始化系统默认信任库 for (TrustManager tm : tmf.getTrustManagers()) { if (tm instanceof X509TrustManager) { return (X509TrustManager) tm; } } } catch (Exception e) { Log.e(TAG, "获取系统默认信任管理器失败", e); } return null; } /** * 从assets载证书 */ private static Certificate loadCertificate(Context context, String fileName) throws CertificateException, IOException { try (InputStream is = context.getAssets().open(fileName)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); return cf.generateCertificate(is); } } /** * 创建包含证书的KeyStore */ private static KeyStore createKeyStoreWithCertificate(Certificate certificate) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); // 创建空KeyStore keyStore.setCertificateEntry("server", certificate); return keyStore; } }
06-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值