From 504d58d63694cadcdfa12ef993c73f6a18592945 Mon Sep 17 00:00:00 2001 From: lijie <675862284@qq.com> Date: Thu, 27 Jul 2023 18:11:12 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/cmx/wanhui/activity/BaseActivity.kt | 102 +++--- .../cmx/wanhui/activity/LoginActivity.java | 6 +- .../com/cmx/wanhui/activity/MainActivity.kt | 165 ++++----- .../com/cmx/wanhui/activity/MyApplication.kt | 57 ++- .../java/com/cmx/wanhui/model/LoginBean.kt | 26 +- .../java/com/cmx/wanhui/model/LoginRes.kt | 51 +-- .../com/cmx/wanhui/retrofit/ApiRequtest.java | 9 +- .../java/com/cmx/wanhui/ui/BaseFragment.kt | 87 +++++ .../java/com/cmx/wanhui/ui/HomeFragment.kt | 316 +++++++---------- .../java/com/cmx/wanhui/ui/ModeFragment.kt | 309 ++++++----------- .../com/cmx/wanhui/ui/PersonalFragment.kt | 126 ++----- .../java/com/cmx/wanhui/utils/AndroidtoJs.kt | 137 ++++---- app/src/main/java/com/cmx/wanhui/utils/L.kt | 130 +++---- .../main/java/com/cmx/wanhui/utils/MyUtils.kt | 326 +++++++++--------- .../main/java/com/cmx/wanhui/utils/SpUtils.kt | 34 +- .../com/cmx/wanhui/utils/StaticFinalData.kt | 14 +- app/src/main/res/values/strings.xml | 2 + 17 files changed, 802 insertions(+), 1095 deletions(-) create mode 100644 app/src/main/java/com/cmx/wanhui/ui/BaseFragment.kt diff --git a/app/src/main/java/com/cmx/wanhui/activity/BaseActivity.kt b/app/src/main/java/com/cmx/wanhui/activity/BaseActivity.kt index 9f2b2e4..c2c752c 100644 --- a/app/src/main/java/com/cmx/wanhui/activity/BaseActivity.kt +++ b/app/src/main/java/com/cmx/wanhui/activity/BaseActivity.kt @@ -1,75 +1,63 @@ -package com.cmx.wanhui.activity; +package com.cmx.wanhui.activity -import android.os.Bundle; -import android.webkit.WebResourceError; -import android.webkit.WebResourceRequest; -import android.webkit.WebView; -import android.webkit.WebViewClient; +import android.os.Bundle +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebView +import android.webkit.WebViewClient +import androidx.appcompat.app.AppCompatActivity +import com.cmx.wanhui.view.BaseLoadingDialog +import com.lsxiao.apollo.core.Apollo +import com.lsxiao.apollo.core.contract.ApolloBinder -import androidx.appcompat.app.AppCompatActivity; - -import com.cmx.wanhui.view.BaseLoadingDialog; -import com.lsxiao.apollo.core.Apollo; -import com.lsxiao.apollo.core.contract.ApolloBinder; - -public class BaseActivity extends AppCompatActivity { - - private static final String TAG = "BaseActivity"; - private BaseLoadingDialog mBaseLoadingDialog; - private ApolloBinder mApolloBinder; - - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mBaseLoadingDialog = new BaseLoadingDialog(this); - mApolloBinder = Apollo.bind(this); +open class BaseActivity : AppCompatActivity() { + private var mBaseLoadingDialog: BaseLoadingDialog? = null + private var mApolloBinder: ApolloBinder? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + mBaseLoadingDialog = BaseLoadingDialog(this) + mApolloBinder = Apollo.bind(this) } - - public void showDialog() { - if (!mBaseLoadingDialog.isShowing()) { - mBaseLoadingDialog.show(); + fun showDialog() { + if (!mBaseLoadingDialog!!.isShowing) { + mBaseLoadingDialog!!.show() } } - - public void disDialog() { - if (mBaseLoadingDialog.isShowing()) { - mBaseLoadingDialog.dismiss(); + fun disDialog() { + if (mBaseLoadingDialog!!.isShowing) { + mBaseLoadingDialog!!.dismiss() } } - public void setWeb(WebView mWebView) { - mWebView.setWebViewClient(new WebViewClient() { - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) { - //使用WebView加载显示url - view.loadUrl(url); - //返回true - return true; - } + fun setWeb(mWebView: WebView) { + mWebView.webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { + //使用WebView加载显示url + view.loadUrl(url) + //返回true + return true + } - @Override - public void onPageFinished(WebView view, String url) { - disDialog(); - } + override fun onPageFinished(view: WebView, url: String) { + disDialog() + } - @Override - public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { - disDialog(); - } - } - - ); + override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) { + disDialog() + } + } } - - @Override - protected void onDestroy() { - super.onDestroy(); + override fun onDestroy() { + super.onDestroy() if (mApolloBinder != null) { - mApolloBinder.unbind(); + mApolloBinder!!.unbind() } } + + companion object { + private const val TAG = "BaseActivity" + } } \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/activity/LoginActivity.java b/app/src/main/java/com/cmx/wanhui/activity/LoginActivity.java index b07eed6..7c12882 100644 --- a/app/src/main/java/com/cmx/wanhui/activity/LoginActivity.java +++ b/app/src/main/java/com/cmx/wanhui/activity/LoginActivity.java @@ -64,7 +64,7 @@ public class LoginActivity extends BaseActivity { disDialog(); if (response.isSuccessful() && response.body().getCode() == 0) { SpUtils.putString(LoginActivity.this, "token", response.body().getAccess_token()); - SpUtils.putString(LoginActivity.this, "admin", response.body().getIs_admin()); + SpUtils.putString(LoginActivity.this, "admin", response.body().is_admin()); Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); @@ -75,8 +75,12 @@ public class LoginActivity extends BaseActivity { @Override public void onFailure(Call call, Throwable t) { + disDialog(); Toasty.info(LoginActivity.this, "登录失败").show(); + Intent intent = new Intent(LoginActivity.this, MainActivity.class); + startActivity(intent); + finish(); } }); } diff --git a/app/src/main/java/com/cmx/wanhui/activity/MainActivity.kt b/app/src/main/java/com/cmx/wanhui/activity/MainActivity.kt index 4c04e44..b42c87b 100644 --- a/app/src/main/java/com/cmx/wanhui/activity/MainActivity.kt +++ b/app/src/main/java/com/cmx/wanhui/activity/MainActivity.kt @@ -1,142 +1,123 @@ -package com.cmx.wanhui.activity; +package com.cmx.wanhui.activity -import android.content.Intent; -import android.os.Build; -import android.os.Bundle; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.Toast; - -import androidx.annotation.RequiresApi; -import androidx.navigation.NavController; -import androidx.navigation.Navigation; -import androidx.navigation.ui.AppBarConfiguration; -import androidx.navigation.ui.NavigationUI; - -import com.cmx.wanhui.R; -import com.cmx.wanhui.constant.Events; -import com.cmx.wanhui.databinding.ActivityMainBinding; -import com.google.android.material.bottomnavigation.BottomNavigationView; -import com.google.zxing.integration.android.IntentIntegrator; -import com.google.zxing.integration.android.IntentResult; -import com.lsxiao.apollo.core.Apollo; -import com.lsxiao.apollo.core.annotations.Receive; - -public class MainActivity extends BaseActivity { - - private ActivityMainBinding binding; - private BottomNavigationView navView; - private NavController navController; +import android.content.Intent +import android.os.Build +import android.os.Bundle +import android.view.View +import android.widget.Toast +import androidx.annotation.RequiresApi +import androidx.navigation.NavController +import androidx.navigation.Navigation +import androidx.navigation.ui.NavigationUI +import com.cmx.wanhui.R +import com.cmx.wanhui.constant.Events +import com.google.zxing.integration.android.IntentIntegrator +import com.lsxiao.apollo.core.Apollo +import com.lsxiao.apollo.core.annotations.Receive +import kotlinx.android.synthetic.main.activity_main.nav_view +class MainActivity : BaseActivity() { + private var navController: NavController? = null @RequiresApi(api = Build.VERSION_CODES.M) - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - binding = ActivityMainBinding.inflate(getLayoutInflater()); - setContentView(binding.getRoot()); - navView = findViewById(R.id.nav_view); - navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main); - NavigationUI.setupWithNavController(binding.navView, navController); + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main) + NavigationUI.setupWithNavController(nav_view, navController!!) } - /** * 显示tabbar */ @Receive(Events.JS_OPEN_TABBAR_SHOW) - public void showTab() { - binding.navView.setVisibility(View.VISIBLE); + fun showTab() { + nav_view.visibility = View.VISIBLE } /** * 隐藏tabbar */ @Receive(Events.JS_OPEN_TABBAR_HIDE) - public void hideTab() { - binding.navView.setVisibility(View.GONE); + fun hideTab() { + nav_view.visibility = View.GONE } - /** * 打开新的web */ @Receive(Events.JS_OPEN_OPEN_WEB) - public void openWeb(String url) { - Intent intent = new Intent(this, WebActivity.class); - intent.putExtra("url", url); - startActivity(intent); + fun openWeb(url: String?) { + val intent = Intent(this, WebActivity::class.java) + intent.putExtra("url", url) + startActivity(intent) } - /** * 选择tab */ @Receive(Events.JS_OPEN_TAB) - public void ckTab(String mode) { - Apollo.emit(Events.JS_OPEN_CLOSE_WEB); - switch (mode) { - case "1": - Menu menu = navView.getMenu(); - MenuItem menuItem = menu.getItem(0); // 将index替换为您想要点击的项目的索引 - menuItem.setChecked(true); - navController.navigate(R.id.navigation_home); - break; - case "2": - Menu menu2 = navView.getMenu(); - MenuItem menuItem2 = menu2.getItem(1); // 将index替换为您想要点击的项目的索引 - menuItem2.setChecked(true); - navController.navigate(R.id.navigation_dashboard); - break; - case "3": - Menu menu3 = navView.getMenu(); - MenuItem menuItem3 = menu3.getItem(2); // 将index替换为您想要点击的项目的索引 - menuItem3.setChecked(true); - navController.navigate(R.id.navigation_notifications); - break; + fun ckTab(mode: String?) { + Apollo.emit(Events.JS_OPEN_CLOSE_WEB) + when (mode) { + "1" -> { + val menu = nav_view!!.menu + val menuItem = menu.getItem(0) // 将index替换为您想要点击的项目的索引 + menuItem.isChecked = true + navController!!.navigate(R.id.navigation_home) + } + + "2" -> { + val menu2 = nav_view!!.menu + val menuItem2 = menu2.getItem(1) // 将index替换为您想要点击的项目的索引 + menuItem2.isChecked = true + navController!!.navigate(R.id.navigation_dashboard) + } + + "3" -> { + val menu3 = nav_view!!.menu + val menuItem3 = menu3.getItem(2) // 将index替换为您想要点击的项目的索引 + menuItem3.isChecked = true + navController!!.navigate(R.id.navigation_notifications) + } } } - /** * 退出登录 */ @Receive(Events.JS_OPEN_LOGOUT) - public void exit() { - Apollo.emit(Events.JS_OPEN_CLOSE_WEB); - finish(); - Intent intent = new Intent(this, LoginActivity.class); - startActivity(intent); + fun exit() { + Apollo.emit(Events.JS_OPEN_CLOSE_WEB) + finish() + val intent = Intent(this, LoginActivity::class.java) + startActivity(intent) } /** * 二维码扫描 */ @Receive(Events.JS_OPEN_SCANQR) - public void scanQR() { - IntentIntegrator integrator = new IntentIntegrator(this); - integrator.setOrientationLocked(true); // 设置扫描方向是否锁定 - integrator.setCaptureActivity(CustomCaptureActivity.class); - integrator.setPrompt("请对准二维码");// 设置提示语 - integrator.initiateScan(); + fun scanQR() { + val integrator = IntentIntegrator(this) + integrator.setOrientationLocked(true) // 设置扫描方向是否锁定 + integrator.captureActivity = CustomCaptureActivity::class.java + integrator.setPrompt("请对准二维码") // 设置提示语 + integrator.initiateScan() } - // 处理扫描结果 - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if (result != null) { - if (result.getContents() == null) { // 扫描取消 + if (result.contents == null) { // 扫描取消 } else { // 扫描成功,处理结果 - String scannedData = result.getContents(); - Apollo.emit(Events.JS_OPEN_SCANQR_BACK, scannedData); - Toast.makeText(this, "扫描结果: " + scannedData, Toast.LENGTH_LONG).show(); + val scannedData = result.contents + Apollo.emit(Events.JS_OPEN_SCANQR_BACK, scannedData) + Toast.makeText(this, "扫描结果: $scannedData", Toast.LENGTH_LONG).show() } } else { - super.onActivityResult(requestCode, resultCode, data); + super.onActivityResult(requestCode, resultCode, data) } } -} - +} \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/activity/MyApplication.kt b/app/src/main/java/com/cmx/wanhui/activity/MyApplication.kt index 0bd3823..27ac2e5 100644 --- a/app/src/main/java/com/cmx/wanhui/activity/MyApplication.kt +++ b/app/src/main/java/com/cmx/wanhui/activity/MyApplication.kt @@ -1,40 +1,35 @@ -package com.cmx.wanhui.activity; +package com.cmx.wanhui.activity -import android.app.Application; -import android.content.Context; +import android.app.Application +import android.content.Context +import com.lsxiao.apollo.core.Apollo +import io.reactivex.android.schedulers.AndroidSchedulers -import com.lsxiao.apollo.core.Apollo; - -import io.reactivex.android.schedulers.AndroidSchedulers; - -public class MyApplication extends Application { - private static MyApplication mInstance; - - private static String mToken; - - @Override - public void onCreate() { - super.onCreate(); - mInstance = this; - Apollo.init(AndroidSchedulers.mainThread(), this); +class MyApplication : Application() { + override fun onCreate() { + super.onCreate() + mInstance = this + Apollo.init(AndroidSchedulers.mainThread(), this) } - - @Override - protected void attachBaseContext(Context base) { - super.attachBaseContext(base); + override fun attachBaseContext(base: Context) { + super.attachBaseContext(base) } + companion object { + private var mInstance: Context? = null + private var mToken: String? = null + @JvmStatic + fun getmInstance(): Context? { + return mInstance + } - public static MyApplication getmInstance() { - return mInstance; - } + fun getmToken(): String? { + return mToken + } - public static String getmToken() { - return mToken; + fun setmToken(mToken: String?) { + Companion.mToken = mToken + } } - - public static void setmToken(String mToken) { - MyApplication.mToken = mToken; - } -} +} \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/model/LoginBean.kt b/app/src/main/java/com/cmx/wanhui/model/LoginBean.kt index b4e246b..2df66b7 100644 --- a/app/src/main/java/com/cmx/wanhui/model/LoginBean.kt +++ b/app/src/main/java/com/cmx/wanhui/model/LoginBean.kt @@ -1,22 +1,6 @@ -package com.cmx.wanhui.model; +package com.cmx.wanhui.model -public class LoginBean { - String username; - String password; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} +class LoginBean { + var username: String? = null + var password: String? = null +} \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/model/LoginRes.kt b/app/src/main/java/com/cmx/wanhui/model/LoginRes.kt index 38415f5..d4ba3d3 100644 --- a/app/src/main/java/com/cmx/wanhui/model/LoginRes.kt +++ b/app/src/main/java/com/cmx/wanhui/model/LoginRes.kt @@ -1,51 +1,14 @@ -package com.cmx.wanhui.model; - - -public class LoginRes { - +package com.cmx.wanhui.model +class LoginRes { /** * code : 0 * message : 登录成功 * access_token : 1914936f8c87fddd11836ebebb65317bb7f57506 * is_admin : 1 */ - - - private int code; - private String message; - private String access_token; - private String is_admin; - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getAccess_token() { - return access_token; - } - - public void setAccess_token(String access_token) { - this.access_token = access_token; - } - - public String getIs_admin() { - return is_admin; - } - - public void setIs_admin(String is_admin) { - this.is_admin = is_admin; - } -} + var code = 0 + var message: String? = null + var access_token: String? = null + var is_admin: String? = null +} \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/retrofit/ApiRequtest.java b/app/src/main/java/com/cmx/wanhui/retrofit/ApiRequtest.java index 30f99e6..ec9e069 100644 --- a/app/src/main/java/com/cmx/wanhui/retrofit/ApiRequtest.java +++ b/app/src/main/java/com/cmx/wanhui/retrofit/ApiRequtest.java @@ -17,21 +17,21 @@ public class ApiRequtest { private TypeToken mResultType; - public ApiRequtest (Call call, TypeToken resultType, final ApiResponse.Listener> listener, final ApiResponse.ErrorListener errorListener){ + public ApiRequtest(Call call, TypeToken resultType, final ApiResponse.Listener> listener, final ApiResponse.ErrorListener errorListener) { mResultType = resultType; call.enqueue(new Callback() { @Override public void onResponse(Call call, retrofit2.Response response) { try { ResponseBody responseBody = response.body(); - if(responseBody != null){ + if (responseBody != null) { String jsonString = response.body().string(); final ApiResult result = new ApiResult<>(new JSONObject(jsonString), mResultType); listener.onResponse(result); } - }catch (IOException e){ - }catch (JSONException e) { + } catch (IOException e) { + } catch (JSONException e) { } } @@ -43,5 +43,4 @@ public class ApiRequtest { } - } diff --git a/app/src/main/java/com/cmx/wanhui/ui/BaseFragment.kt b/app/src/main/java/com/cmx/wanhui/ui/BaseFragment.kt new file mode 100644 index 0000000..fa201d5 --- /dev/null +++ b/app/src/main/java/com/cmx/wanhui/ui/BaseFragment.kt @@ -0,0 +1,87 @@ +package com.cmx.wanhui.ui + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebSettings +import android.webkit.WebView +import android.webkit.WebViewClient +import androidx.fragment.app.Fragment +import com.cmx.wanhui.utils.AndroidtoJs +import com.cmx.wanhui.utils.MyUtils +import com.cmx.wanhui.view.BaseLoadingDialog +import com.lsxiao.apollo.core.Apollo +import com.lsxiao.apollo.core.contract.ApolloBinder + +open class BaseFragment : Fragment() { + + var mBaseLoadingDialog: BaseLoadingDialog? = null + var mApolloBinder: ApolloBinder? = null + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(null, container, false) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + mBaseLoadingDialog = BaseLoadingDialog(activity) + MyUtils.setFullscreen(requireActivity(), false, false) + MyUtils.setAndroidNativeLightStatusBar(requireActivity(), true) + mApolloBinder = Apollo.bind(this) + } + + + /** + * 相关属性设置 + */ + fun setVebView(webView: WebView) { + val webSettings = webView!!.settings + webSettings.javaScriptEnabled = true + webSettings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK + webSettings.domStorageEnabled = true + webSettings.allowFileAccess = true //文件访问 + webSettings.allowFileAccessFromFileURLs = true + webView!!.addJavascriptInterface(AndroidtoJs(), "AndroidtoJs") + webView!!.webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { + //使用WebView加载显示url + view.loadUrl(url) + //返回true + return true + } + + override fun onPageFinished(view: WebView, url: String) { + disDialog() + } + + override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) { + disDialog() + } + } + } + + + override fun onDestroyView() { + super.onDestroyView() + if (mApolloBinder != null) { + mApolloBinder!!.unbind() + } + } + + fun showDialog() { + mBaseLoadingDialog = BaseLoadingDialog(activity) + if (!mBaseLoadingDialog!!.isShowing) { + mBaseLoadingDialog!!.show() + } + } + + fun disDialog() { + if (mBaseLoadingDialog!!.isShowing) { + mBaseLoadingDialog!!.dismiss() + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/ui/HomeFragment.kt b/app/src/main/java/com/cmx/wanhui/ui/HomeFragment.kt index 9428675..2302d59 100644 --- a/app/src/main/java/com/cmx/wanhui/ui/HomeFragment.kt +++ b/app/src/main/java/com/cmx/wanhui/ui/HomeFragment.kt @@ -1,239 +1,161 @@ -package com.cmx.wanhui.ui; +package com.cmx.wanhui.ui -import static com.cmx.wanhui.constant.Events.SERVER_URL; +import android.app.Activity +import android.content.ClipData +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.os.Environment +import android.provider.MediaStore +import android.util.Log +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.webkit.ValueCallback +import android.webkit.WebChromeClient +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebSettings +import android.webkit.WebView +import android.webkit.WebViewClient +import androidx.fragment.app.Fragment +import com.cmx.wanhui.R +import com.cmx.wanhui.constant.Events +import com.cmx.wanhui.utils.AndroidtoJs +import com.cmx.wanhui.utils.L +import com.cmx.wanhui.utils.MyUtils +import com.cmx.wanhui.view.BaseLoadingDialog +import com.lsxiao.apollo.core.Apollo +import com.lsxiao.apollo.core.annotations.Receive +import kotlinx.android.synthetic.main.fragment_home.tv_te +import kotlinx.android.synthetic.main.fragment_home.wv_home +import java.io.File +import java.io.IOException +import java.text.SimpleDateFormat +import java.util.Date -import android.app.Activity; -import android.content.ClipData; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Environment; -import android.provider.MediaStore; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.webkit.ValueCallback; -import android.webkit.WebChromeClient; -import android.webkit.WebResourceError; -import android.webkit.WebResourceRequest; -import android.webkit.WebSettings; -import android.webkit.WebView; -import android.webkit.WebViewClient; +class HomeFragment : BaseFragment() { -import androidx.annotation.NonNull; -import androidx.fragment.app.Fragment; -import androidx.lifecycle.ViewModelProvider; - -import com.cmx.wanhui.activity.LoginActivity; -import com.cmx.wanhui.constant.Events; -import com.cmx.wanhui.databinding.FragmentHomeBinding; -import com.cmx.wanhui.utils.AndroidtoJs; -import com.cmx.wanhui.utils.L; -import com.cmx.wanhui.utils.MyUtils; -import com.cmx.wanhui.view.BaseLoadingDialog; -import com.lsxiao.apollo.core.Apollo; -import com.lsxiao.apollo.core.annotations.Receive; -import com.lsxiao.apollo.core.contract.ApolloBinder; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class HomeFragment extends Fragment { - - private FragmentHomeBinding binding; - private BaseLoadingDialog mBaseLoadingDialog; - private WebView mWebView; - private ApolloBinder mApolloBinder; - private ValueCallback mUploadMessage; - private String mCameraPhotoPath = null; - private long size = 0; - private static final int INPUT_FILE_REQUEST_CODE = 1; + private var mUploadMessage: ValueCallback>? = null + private var mCameraPhotoPath: String? = null + private var size: Long = 0 - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - binding = FragmentHomeBinding.inflate(inflater, container, false); - mBaseLoadingDialog = new BaseLoadingDialog(getActivity()); - View root = binding.getRoot(); - MyUtils.setFullscreen(requireActivity(), false, false); - MyUtils.setAndroidNativeLightStatusBar(requireActivity(), true); - mWebView = binding.wvHome; - mApolloBinder = Apollo.bind(this); - WebSettings webSettings = mWebView.getSettings(); - webSettings.setJavaScriptEnabled(true); - webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); - webSettings.setDomStorageEnabled(true); - webSettings.setAllowFileAccess(true);//文件访问 - webSettings.setAllowFileAccessFromFileURLs(true); - mWebView.addJavascriptInterface(new AndroidtoJs(), "AndroidtoJs"); - // mWebView.loadUrl(SERVER_URL + "/nigeria/?lang=English#/index"); - mWebView.loadUrl("https://www.baidu.com/"); - showDialog(); - mWebView.setWebChromeClient(new PQChromeClient()); - mWebView.setWebViewClient(new WebViewClient() { - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) { - //使用WebView加载显示url - view.loadUrl(url); - //返回true - return true; - } - - @Override - public void onPageFinished(WebView view, String url) { - disDialog(); - } - - @Override - public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { - disDialog(); - } - } - - ); - - binding.tvTe.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Apollo.emit(Events.JS_OPEN_SCANQR); - } - }); - return root; + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_home, container, false) } - @Override - public void onDestroyView() { - super.onDestroyView(); - binding = null; - if (mApolloBinder != null) { - mApolloBinder.unbind(); - } + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + setVebView(wv_home!!) + wv_home!!.loadUrl("https://www.baidu.com/")//SERVER_URL + showDialog() + wv_home!!.webChromeClient = PQChromeClient() + tv_te.setOnClickListener { Apollo.emit(Events.JS_OPEN_SCANQR) } } - public void showDialog() { - mBaseLoadingDialog = new BaseLoadingDialog(getActivity()); - if (!mBaseLoadingDialog.isShowing()) { - mBaseLoadingDialog.show(); - } - } - public void disDialog() { - if (mBaseLoadingDialog.isShowing()) { - mBaseLoadingDialog.dismiss(); - } - } - - - public class PQChromeClient extends WebChromeClient { + inner class PQChromeClient : WebChromeClient() { // For Android 5.0+ - public boolean onShowFileChooser(WebView view, ValueCallback filePath, WebChromeClient.FileChooserParams fileChooserParams) { + override fun onShowFileChooser( + view: WebView, filePath: ValueCallback>, fileChooserParams: FileChooserParams + ): Boolean { // Double check that we don't have any existing callbacks if (mUploadMessage != null) { - mUploadMessage.onReceiveValue(null); + mUploadMessage!!.onReceiveValue(null) } - mUploadMessage = filePath; - Log.e("FileCooserParams => ", filePath.toString()); - Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); - if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) { + mUploadMessage = filePath + Log.e("FileCooserParams => ", filePath.toString()) + var takePictureIntent: Intent? = Intent(MediaStore.ACTION_IMAGE_CAPTURE) + if (takePictureIntent!!.resolveActivity(activity!!.packageManager) != null) { // Create the File where the photo should go - File photoFile = null; + var photoFile: File? = null try { - photoFile = createImageFile(); - takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath); - } catch (IOException ex) { + photoFile = createImageFile() + takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath) + } catch (ex: IOException) { // Error occurred while creating the File - Log.e("test", "Unable to create Image File", ex); + Log.e("test", "Unable to create Image File", ex) } // Continue only if the File was successfully created if (photoFile != null) { - mCameraPhotoPath = "file:" + photoFile.getAbsolutePath(); - takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); + mCameraPhotoPath = "file:" + photoFile.absolutePath + takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)) } else { - takePictureIntent = null; + takePictureIntent = null } } - - Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); - contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); - contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); - contentSelectionIntent.setType("image/*"); - Intent[] intentArray; - if (takePictureIntent != null) { - intentArray = new Intent[]{takePictureIntent}; - } else { - intentArray = new Intent[2]; - } - Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); - chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); - chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser"); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); - startActivityForResult(Intent.createChooser(chooserIntent, "Select images"), 1); - return true; + val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT) + contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE) + contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) + contentSelectionIntent.type = "image/*" + val intentArray: Array + intentArray = takePictureIntent?.let { arrayOf(it) } ?: arrayOfNulls(2) + val chooserIntent = Intent(Intent.ACTION_CHOOSER) + chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent) + chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser") + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray) + startActivityForResult(Intent.createChooser(chooserIntent, "Select images"), 1) + return true } } - - private File createImageFile() throws IOException { + @Throws(IOException::class) + private fun createImageFile(): File { // Create an image file name - String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); - String imageFileName = "JPEG_" + timeStamp + "_"; - File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); - File imageFile = File.createTempFile(imageFileName, /* prefix */ - ".jpg", /* suffix */ - storageDir /* directory */); - return imageFile; + val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) + val imageFileName = "JPEG_" + timeStamp + "_" + val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + return File.createTempFile( + imageFileName, /* prefix */ + ".jpg", /* suffix */ + storageDir /* directory */ + ) } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode != INPUT_FILE_REQUEST_CODE || mUploadMessage == null) { - super.onActivityResult(requestCode, resultCode, data); - return; + super.onActivityResult(requestCode, resultCode, data) + return } try { - String file_path = mCameraPhotoPath.replace("file:", ""); - File file = new File(file_path); - size = file.length(); + val file_path = mCameraPhotoPath!!.replace("file:", "") + val file = File(file_path) + size = file.length() if (data != null || mCameraPhotoPath != null) { - Integer count = 1; - ClipData images = null; + var count = 1 + var images: ClipData? = null try { - images = data.getClipData(); - } catch (Exception e) { - Log.e("Error!", e.getLocalizedMessage()); + images = data!!.clipData + } catch (e: Exception) { + Log.e("Error!", e.localizedMessage) } - - if (images == null && data != null && data.getDataString() != null) { - count = data.getDataString().length(); + if (images == null && data != null && data.dataString != null) { + count = data.dataString!!.length } else if (images != null) { - count = images.getItemCount(); + count = images.itemCount } - Uri[] results = new Uri[count]; - // Check that the response is a good one + var results = arrayOfNulls(count) if (resultCode == Activity.RESULT_OK) { - if (size != 0) { + if (size != 0L) { // If there is not data, then we may have taken a photo if (mCameraPhotoPath != null) { - results = new Uri[]{Uri.parse(mCameraPhotoPath)}; + results = arrayOf(Uri.parse(mCameraPhotoPath)) } - } else if (data.getClipData() == null) { - results = new Uri[]{Uri.parse(data.getDataString())}; + } else if (data!!.clipData == null) { + results = arrayOf(Uri.parse(data.dataString)) } else { - - for (int i = 0; i < images.getItemCount(); i++) { - results[i] = images.getItemAt(i).getUri(); + for (i in 0 until images!!.itemCount) { + results[i] = images.getItemAt(i).uri } } } - mUploadMessage.onReceiveValue(results); - mUploadMessage = null; + //mUploadMessage!!.onReceiveValue(results) + mUploadMessage = null } - } catch (Exception e) { - Log.e("Error!", "Error while opening image file" + e.getLocalizedMessage()); + } catch (e: Exception) { + Log.e("Error!", "Error while opening image file" + e.localizedMessage) } } @@ -241,13 +163,13 @@ public class HomeFragment extends Fragment { * 二维码扫描返回 */ @Receive(Events.JS_OPEN_SCANQR_BACK) - public void onQRBack(String msg) { - String jsString = "javascript:onQRBack(" + msg + ")"; - L.e("JS二维码扫描返回>>>>", jsString); - mWebView.evaluateJavascript(jsString, new ValueCallback() { - @Override - public void onReceiveValue(String s) { - } - }); + fun onQRBack(msg: String) { + val jsString = "javascript:onQRBack($msg)" + L.e("JS二维码扫描返回>>>>", jsString) + wv_home!!.evaluateJavascript(jsString) { } + } + + companion object { + private const val INPUT_FILE_REQUEST_CODE = 1 } } \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/ui/ModeFragment.kt b/app/src/main/java/com/cmx/wanhui/ui/ModeFragment.kt index aa72520..425bf11 100644 --- a/app/src/main/java/com/cmx/wanhui/ui/ModeFragment.kt +++ b/app/src/main/java/com/cmx/wanhui/ui/ModeFragment.kt @@ -1,236 +1,155 @@ -package com.cmx.wanhui.ui; +package com.cmx.wanhui.ui -import static com.cmx.wanhui.constant.Events.SERVER_URL; +import android.app.Activity +import android.content.ClipData +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.os.Environment +import android.provider.MediaStore +import android.util.Log +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.webkit.ValueCallback +import android.webkit.WebChromeClient +import android.webkit.WebView +import com.cmx.wanhui.R +import com.cmx.wanhui.constant.Events +import com.cmx.wanhui.utils.L +import com.lsxiao.apollo.core.Apollo +import com.lsxiao.apollo.core.annotations.Receive +import kotlinx.android.synthetic.main.fragment_dashboard.wv_loan +import kotlinx.android.synthetic.main.fragment_home.tv_te +import java.io.File +import java.io.IOException +import java.text.SimpleDateFormat +import java.util.Date -import android.app.Activity; -import android.content.ClipData; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Environment; -import android.provider.MediaStore; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.webkit.ValueCallback; -import android.webkit.WebChromeClient; -import android.webkit.WebResourceError; -import android.webkit.WebResourceRequest; -import android.webkit.WebSettings; -import android.webkit.WebView; -import android.webkit.WebViewClient; - -import androidx.annotation.NonNull; -import androidx.fragment.app.Fragment; - -import com.cmx.wanhui.constant.Events; -import com.cmx.wanhui.databinding.FragmentDashboardBinding; -import com.cmx.wanhui.utils.AndroidtoJs; -import com.cmx.wanhui.utils.L; -import com.cmx.wanhui.utils.MyUtils; -import com.cmx.wanhui.view.BaseLoadingDialog; -import com.lsxiao.apollo.core.Apollo; -import com.lsxiao.apollo.core.annotations.Receive; -import com.lsxiao.apollo.core.contract.ApolloBinder; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class ModeFragment extends Fragment { - - private FragmentDashboardBinding binding; - private BaseLoadingDialog mBaseLoadingDialog; - private WebView mWebView; - private ApolloBinder mApolloBinder; - private ValueCallback mUploadMessage; - private String mCameraPhotoPath = null; - private long size = 0; - private static final int INPUT_FILE_REQUEST_CODE = 1; +class ModeFragment : BaseFragment() { + private var mUploadMessage: ValueCallback>? = null + private var mCameraPhotoPath: String? = null + private var size: Long = 0 - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - binding = FragmentDashboardBinding.inflate(inflater, container, false); - mBaseLoadingDialog = new BaseLoadingDialog(getActivity()); - View root = binding.getRoot(); - MyUtils.setFullscreen(requireActivity(), false, false); - MyUtils.setAndroidNativeLightStatusBar(requireActivity(), true); - mWebView = binding.wvLoan; - mApolloBinder = Apollo.bind(this); - WebSettings webSettings = mWebView.getSettings(); - webSettings.setJavaScriptEnabled(true); - webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); - webSettings.setDomStorageEnabled(true); - webSettings.setAllowFileAccess(true);//文件访问 - webSettings.setAllowFileAccessFromFileURLs(true); - mWebView.addJavascriptInterface(new AndroidtoJs(), "AndroidtoJs"); - // mWebView.loadUrl(SERVER_URL + "/nigeria/?lang=English#/loans"); - mWebView.loadUrl("https://www.baidu.com/"); - showDialog(); - mWebView.setWebChromeClient(new PQChromeClient()); - mWebView.setWebViewClient(new WebViewClient() { - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) { - //使用WebView加载显示url - view.loadUrl(url); - //返回true - return true; - } + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_dashboard, container, false) + } - @Override - public void onPageFinished(WebView view, String url) { - disDialog(); - } - - @Override - public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { - disDialog(); - } - } - - ); - return root; + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + setVebView(wv_loan!!) + wv_loan!!.loadUrl("https://www.baidu.com/")//SERVER_URL + showDialog() + wv_loan!!.webChromeClient = PQChromeClient() } - @Override - public void onDestroyView() { - super.onDestroyView(); - binding = null; - if (mApolloBinder != null) { - mApolloBinder.unbind(); - } - } - - - public void showDialog() { - mBaseLoadingDialog = new BaseLoadingDialog(getActivity()); - if (!mBaseLoadingDialog.isShowing()) { - mBaseLoadingDialog.show(); - } - } - - - public void disDialog() { - if (mBaseLoadingDialog.isShowing()) { - mBaseLoadingDialog.dismiss(); - } - } - - - public class PQChromeClient extends WebChromeClient { + inner class PQChromeClient : WebChromeClient() { // For Android 5.0+ - public boolean onShowFileChooser(WebView view, ValueCallback filePath, WebChromeClient.FileChooserParams fileChooserParams) { + override fun onShowFileChooser( + view: WebView, + filePath: ValueCallback>, + fileChooserParams: FileChooserParams + ): Boolean { // Double check that we don't have any existing callbacks if (mUploadMessage != null) { - mUploadMessage.onReceiveValue(null); + mUploadMessage!!.onReceiveValue(null) } - mUploadMessage = filePath; - Log.e("FileCooserParams => ", filePath.toString()); - Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); - if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) { + mUploadMessage = filePath + Log.e("FileCooserParams => ", filePath.toString()) + var takePictureIntent: Intent? = Intent(MediaStore.ACTION_IMAGE_CAPTURE) + if (takePictureIntent!!.resolveActivity(activity!!.packageManager) != null) { // Create the File where the photo should go - File photoFile = null; + var photoFile: File? = null try { - photoFile = createImageFile(); - takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath); - } catch (IOException ex) { + photoFile = createImageFile() + takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath) + } catch (ex: IOException) { // Error occurred while creating the File - Log.e("test", "Unable to create Image File", ex); + Log.e("test", "Unable to create Image File", ex) } // Continue only if the File was successfully created if (photoFile != null) { - mCameraPhotoPath = "file:" + photoFile.getAbsolutePath(); - takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); + mCameraPhotoPath = "file:" + photoFile.absolutePath + takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)) } else { - takePictureIntent = null; + takePictureIntent = null } } - - Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); - contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); - contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); - contentSelectionIntent.setType("image/*"); - - Intent[] intentArray; - if (takePictureIntent != null) { - intentArray = new Intent[]{takePictureIntent}; - } else { - intentArray = new Intent[2]; - } - Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); - chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); - chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser"); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); - startActivityForResult(Intent.createChooser(chooserIntent, "Select images"), 1); - - return true; + val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT) + contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE) + contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) + contentSelectionIntent.type = "image/*" + val intentArray: Array + intentArray = takePictureIntent?.let { arrayOf(it) } ?: arrayOfNulls(2) + val chooserIntent = Intent(Intent.ACTION_CHOOSER) + chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent) + chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser") + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray) + startActivityForResult(Intent.createChooser(chooserIntent, "Select images"), 1) + return true } } - - private File createImageFile() throws IOException { + @Throws(IOException::class) + private fun createImageFile(): File { // Create an image file name - String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); - String imageFileName = "JPEG_" + timeStamp + "_"; - File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); - File imageFile = File.createTempFile(imageFileName, /* prefix */ - ".jpg", /* suffix */ - storageDir /* directory */); - return imageFile; + val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) + val imageFileName = "JPEG_" + timeStamp + "_" + val storageDir = + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + return File.createTempFile( + imageFileName, /* prefix */ + ".jpg", /* suffix */ + storageDir /* directory */ + ) } - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode != INPUT_FILE_REQUEST_CODE || mUploadMessage == null) { - super.onActivityResult(requestCode, resultCode, data); - return; + super.onActivityResult(requestCode, resultCode, data) + return } try { - String file_path = mCameraPhotoPath.replace("file:", ""); - File file = new File(file_path); - size = file.length(); - - } catch (Exception e) { - Log.e("Error!", "Error while opening image file" + e.getLocalizedMessage()); + val file_path = mCameraPhotoPath!!.replace("file:", "") + val file = File(file_path) + size = file.length() + } catch (e: Exception) { + Log.e("Error!", "Error while opening image file" + e.localizedMessage) } - if (data != null || mCameraPhotoPath != null) { - Integer count = 1; - ClipData images = null; + var count = 1 + var images: ClipData? = null try { - images = data.getClipData(); - } catch (Exception e) { - Log.e("Error!", e.getLocalizedMessage()); + images = data!!.clipData + } catch (e: Exception) { + Log.e("Error!", e.localizedMessage) } - - if (images == null && data != null && data.getDataString() != null) { - count = data.getDataString().length(); + if (images == null && data != null && data.dataString != null) { + count = data.dataString!!.length } else if (images != null) { - count = images.getItemCount(); + count = images.itemCount } - Uri[] results = new Uri[count]; + var results = arrayOfNulls(count) // Check that the response is a good one if (resultCode == Activity.RESULT_OK) { - if (size != 0) { + if (size != 0L) { // If there is not data, then we may have taken a photo if (mCameraPhotoPath != null) { - results = new Uri[]{Uri.parse(mCameraPhotoPath)}; + results = arrayOf(Uri.parse(mCameraPhotoPath)) } - } else if (data.getClipData() == null) { - results = new Uri[]{Uri.parse(data.getDataString())}; + } else if (data!!.clipData == null) { + results = arrayOf(Uri.parse(data.dataString)) } else { - - for (int i = 0; i < images.getItemCount(); i++) { - results[i] = images.getItemAt(i).getUri(); + for (i in 0 until images!!.itemCount) { + results[i] = images.getItemAt(i).uri } } } - mUploadMessage.onReceiveValue(results); - mUploadMessage = null; + //mUploadMessage!!.onReceiveValue(results) + mUploadMessage = null } } @@ -238,13 +157,13 @@ public class ModeFragment extends Fragment { * 二维码扫描返回 */ @Receive(Events.JS_OPEN_SCANQR_BACK) - public void onQRBack(String msg) { - String jsString = "javascript:onQRBack(" + msg + ")"; - L.e("JS二维码扫描返回>>>>", jsString); - mWebView.evaluateJavascript(jsString, new ValueCallback() { - @Override - public void onReceiveValue(String s) { - } - }); + fun onQRBack(msg: String) { + val jsString = "javascript:onQRBack($msg)" + L.e("JS二维码扫描返回>>>>", jsString) + wv_loan!!.evaluateJavascript(jsString) { } + } + + companion object { + private const val INPUT_FILE_REQUEST_CODE = 1 } } \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/ui/PersonalFragment.kt b/app/src/main/java/com/cmx/wanhui/ui/PersonalFragment.kt index d62db17..75240ec 100644 --- a/app/src/main/java/com/cmx/wanhui/ui/PersonalFragment.kt +++ b/app/src/main/java/com/cmx/wanhui/ui/PersonalFragment.kt @@ -1,116 +1,40 @@ -package com.cmx.wanhui.ui; +package com.cmx.wanhui.ui -import static com.cmx.wanhui.constant.Events.SERVER_URL; +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import com.cmx.wanhui.R +import com.cmx.wanhui.constant.Events +import com.cmx.wanhui.utils.L +import com.lsxiao.apollo.core.Apollo +import com.lsxiao.apollo.core.annotations.Receive +import kotlinx.android.synthetic.main.fragment_home.tv_te +import kotlinx.android.synthetic.main.fragment_notifications.wv_mine -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.webkit.ValueCallback; -import android.webkit.WebResourceError; -import android.webkit.WebResourceRequest; -import android.webkit.WebSettings; -import android.webkit.WebView; -import android.webkit.WebViewClient; - -import androidx.annotation.NonNull; -import androidx.fragment.app.Fragment; - -import com.cmx.wanhui.constant.Events; -import com.cmx.wanhui.databinding.FragmentNotificationsBinding; -import com.cmx.wanhui.utils.AndroidtoJs; -import com.cmx.wanhui.utils.L; -import com.cmx.wanhui.utils.MyUtils; -import com.cmx.wanhui.view.BaseLoadingDialog; -import com.lsxiao.apollo.core.Apollo; -import com.lsxiao.apollo.core.annotations.Receive; -import com.lsxiao.apollo.core.contract.ApolloBinder; - -public class PersonalFragment extends Fragment { - - private FragmentNotificationsBinding binding; - private BaseLoadingDialog mBaseLoadingDialog; - private WebView mWebView; - private ApolloBinder mApolloBinder; +class PersonalFragment : BaseFragment() { - - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - binding = FragmentNotificationsBinding.inflate(inflater, container, false); - mBaseLoadingDialog = new BaseLoadingDialog(getActivity()); - View root = binding.getRoot(); - mApolloBinder = Apollo.bind(this); - MyUtils.setFullscreen(requireActivity(), false, false); - MyUtils.setAndroidNativeLightStatusBar(requireActivity(), true); - mWebView = binding.wvMine; - WebSettings webSettings = mWebView.getSettings(); - webSettings.setJavaScriptEnabled(true); - webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); - webSettings.setDomStorageEnabled(true); - mWebView.addJavascriptInterface(new AndroidtoJs(), "AndroidtoJs"); - // mWebView.loadUrl(SERVER_URL + "/nigeria/?lang=English#/my"); - mWebView.loadUrl("https://www.baidu.com/"); - showDialog(); - mWebView.setWebViewClient(new WebViewClient() { - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) { - //使用WebView加载显示url - view.loadUrl(url); - //返回true - return true; - } - - @Override - public void onPageFinished(WebView view, String url) { - disDialog(); - } - - @Override - public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { - disDialog(); - } - } - - ); - return root; + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_notifications, container, false) } - - @Override - public void onDestroyView() { - super.onDestroyView(); - binding = null; - if (mApolloBinder != null) { - mApolloBinder.unbind(); - } + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + setVebView(wv_mine!!) + wv_mine!!.loadUrl("https://www.baidu.com/")//SERVER_URL + showDialog() + //wv_mine!!.webChromeClient = PQChromeClient() } - public void showDialog() { - mBaseLoadingDialog = new BaseLoadingDialog(getActivity()); - if (!mBaseLoadingDialog.isShowing()) { - mBaseLoadingDialog.show(); - } - } - - - public void disDialog() { - if (mBaseLoadingDialog.isShowing()) { - mBaseLoadingDialog.dismiss(); - } - } /** * 二维码扫描返回 */ @Receive(Events.JS_OPEN_SCANQR_BACK) - public void onQRBack(String msg) { - String jsString = "javascript:onQRBack(" + msg + ")"; - L.e("JS二维码扫描返回>>>>", jsString); - mWebView.evaluateJavascript(jsString, new ValueCallback() { - @Override - public void onReceiveValue(String s) { - } - }); + fun onQRBack(msg: String) { + val jsString = "javascript:onQRBack($msg)" + L.e("JS二维码扫描返回>>>>", jsString) + wv_mine!!.evaluateJavascript(jsString) { } } - } \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/utils/AndroidtoJs.kt b/app/src/main/java/com/cmx/wanhui/utils/AndroidtoJs.kt index 1e9e474..e65f10a 100644 --- a/app/src/main/java/com/cmx/wanhui/utils/AndroidtoJs.kt +++ b/app/src/main/java/com/cmx/wanhui/utils/AndroidtoJs.kt @@ -1,95 +1,94 @@ -package com.cmx.wanhui.utils; +package com.cmx.wanhui.utils -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.util.Log; -import android.webkit.JavascriptInterface; - -import com.cmx.wanhui.constant.Events; -import com.cmx.wanhui.activity.MyApplication; -import com.lsxiao.apollo.core.Apollo; - -public class AndroidtoJs { - private static final String TAG = "cmx_AndroidtoJs"; +import android.content.pm.PackageManager +import android.util.Log +import android.webkit.JavascriptInterface +import com.cmx.wanhui.activity.MyApplication.Companion.getmInstance +import com.cmx.wanhui.constant.Events +import com.lsxiao.apollo.core.Apollo +class AndroidtoJs { // 定义JS需要调用的方法 // 被JS调用的方法必须加入@JavascriptInterface注解 - @JavascriptInterface - public String getAppToken() { - L.e("JS--", "getAppToken()"); - return SpUtils.getString(MyApplication.getmInstance(), "token"); - } + @get:JavascriptInterface + val appToken: String? + get() { + L.e("JS--", "getAppToken()") + return SpUtils.getString(getmInstance()!!, "token") + } /** * 用户角色类型 * * @return */ - @JavascriptInterface - public String getUser() { - L.e("JS--", "getUser()"); - return SpUtils.getString(MyApplication.getmInstance(), "admin"); - } - - - @JavascriptInterface - public String getAppVersion() { - L.e("JS--", "getAppVersion()"); - String versionname;//版本号 - try { - PackageManager pm = MyApplication.getmInstance().getApplicationContext().getPackageManager(); - PackageInfo pi = pm.getPackageInfo(MyApplication.getmInstance().getApplicationContext().getPackageName(), 0); - versionname = "V" + pi.versionName; - } catch (PackageManager.NameNotFoundException e) { - versionname = "未知"; + @get:JavascriptInterface + val user: String? + get() { + L.e("JS--", "getUser()") + return SpUtils.getString(getmInstance()!!, "admin") } - Log.e(TAG, "getAppVersion=" + versionname); - return versionname; + + //版本号 + @get:JavascriptInterface + val appVersion: String + get() { + L.e("JS--", "getAppVersion()") + val versionname: String //版本号 + versionname = try { + val pm = getmInstance()!!.applicationContext.packageManager + val pi = pm.getPackageInfo(getmInstance()!!.applicationContext.packageName, 0) + "V" + pi.versionName + } catch (e: PackageManager.NameNotFoundException) { + "未知" + } + Log.e(TAG, "getAppVersion=$versionname") + return versionname + } + + @JavascriptInterface + fun existApp() { + L.e("JS--", "existApp()") + Apollo.emit(Events.JS_OPEN_LOGOUT) } @JavascriptInterface - public void existApp() { - L.e("JS--", "existApp()"); - Apollo.emit(Events.JS_OPEN_LOGOUT); + fun showTab() { //tabbar显示 + L.e("JS--", "showTab()") + Apollo.emit(Events.JS_OPEN_TABBAR_SHOW) } @JavascriptInterface - public void showTab() {//tabbar显示 - L.e("JS--", "showTab()"); - Apollo.emit(Events.JS_OPEN_TABBAR_SHOW); + fun hideTab() { //tabbar隐藏 + L.e("JS--", "hideTab()") + Apollo.emit(Events.JS_OPEN_TABBAR_HIDE) } @JavascriptInterface - public void hideTab() {//tabbar隐藏 - L.e("JS--", "hideTab()"); - Apollo.emit(Events.JS_OPEN_TABBAR_HIDE); - } - - - @JavascriptInterface - public void openWeb(String url) {//打开一个新的web界面 - L.e("JS--", "openWeb()" + url); - Apollo.emit(Events.JS_OPEN_OPEN_WEB, url); - } - - - @JavascriptInterface - public void closeWeb() {//关闭那个新的web界面 - L.e("JS--", "closeWeb()"); - Apollo.emit(Events.JS_OPEN_CLOSE_WEB); - } - - - @JavascriptInterface - public void checkTab(String mode) {//关闭注册/忘记密码 - L.e("JS--", "checkTab()"); - Apollo.emit(Events.JS_OPEN_TAB, mode); + fun openWeb(url: String) { //打开一个新的web界面 + L.e("JS--", "openWeb()$url") + Apollo.emit(Events.JS_OPEN_OPEN_WEB, url) } @JavascriptInterface - public void scanQR() {//扫描二维码 - L.e("JS--", "scanQR()"); - Apollo.emit(Events.JS_OPEN_SCANQR); + fun closeWeb() { //关闭那个新的web界面 + L.e("JS--", "closeWeb()") + Apollo.emit(Events.JS_OPEN_CLOSE_WEB) } + @JavascriptInterface + fun checkTab(mode: String?) { //关闭注册/忘记密码 + L.e("JS--", "checkTab()") + Apollo.emit(Events.JS_OPEN_TAB, mode!!) + } + + @JavascriptInterface + fun scanQR() { //扫描二维码 + L.e("JS--", "scanQR()") + Apollo.emit(Events.JS_OPEN_SCANQR) + } + + companion object { + private const val TAG = "cmx_AndroidtoJs" + } } \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/utils/L.kt b/app/src/main/java/com/cmx/wanhui/utils/L.kt index 105cb35..37beb58 100644 --- a/app/src/main/java/com/cmx/wanhui/utils/L.kt +++ b/app/src/main/java/com/cmx/wanhui/utils/L.kt @@ -1,92 +1,50 @@ -package com.cmx.wanhui.utils; +package com.cmx.wanhui.utils -import android.content.ContentResolver; -import android.content.Context; -import android.content.Intent; -import android.database.Cursor; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.net.Uri; -import android.os.Build; -import android.provider.MediaStore; -import android.util.Base64; -import android.util.Log; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ListAdapter; -import android.widget.ListView; +import android.util.Log -import java.io.File; -import java.lang.reflect.Method; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - - -public class L { - private L() { - throw new UnsupportedOperationException("cannot be instantiated"); +class L private constructor() { + init { + throw UnsupportedOperationException("cannot be instantiated") } - public static boolean isDebug = true; - private static String TAG = "LjTestLog"; + companion object { + var isDebug = true + var tAG = "LjTestLog" + fun setDebugMode(debug: Boolean) { + isDebug = debug + } - public static String getTAG() { - return TAG; + fun i(msg: String?) { + if (isDebug) Log.i(tAG, msg!!) + } + + fun d(msg: String?) { + if (isDebug) Log.d(tAG, msg!!) + } + + fun e(msg: String?) { + if (isDebug) Log.e(tAG, msg!!) + } + + fun v(msg: String?) { + if (isDebug) Log.v(tAG, msg!!) + } + + fun i(tag: String?, msg: String?) { + if (isDebug) Log.i(tag, msg!!) + } + + fun d(tag: String?, msg: String?) { + if (isDebug) Log.d(tag, msg!!) + } + + @JvmStatic + fun e(tag: String?, msg: String?) { + if (isDebug) Log.e(tag, msg!!) + } + + fun v(tag: String?, msg: String?) { + if (isDebug) Log.v(tag, msg!!) + } } - - public static void setTAG(String TAG) { - L.TAG = TAG; - } - - public static void setDebugMode(boolean debug) { - isDebug = debug; - } - - public static void i(String msg) { - if (isDebug) - Log.i(TAG, msg); - } - - public static void d(String msg) { - if (isDebug) - Log.d(TAG, msg); - } - - public static void e(String msg) { - if (isDebug) - Log.e(TAG, msg); - } - - public static void v(String msg) { - if (isDebug) - Log.v(TAG, msg); - } - - public static void i(String tag, String msg) { - if (isDebug) - Log.i(tag, msg); - } - - public static void d(String tag, String msg) { - if (isDebug) - Log.d(tag, msg); - } - - public static void e(String tag, String msg) { - if (isDebug) - Log.e(tag, msg); - } - - public static void v(String tag, String msg) { - if (isDebug) - Log.v(tag, msg); - - } - - -} - - - +} \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/utils/MyUtils.kt b/app/src/main/java/com/cmx/wanhui/utils/MyUtils.kt index 33c0ad2..d0faf77 100644 --- a/app/src/main/java/com/cmx/wanhui/utils/MyUtils.kt +++ b/app/src/main/java/com/cmx/wanhui/utils/MyUtils.kt @@ -1,180 +1,169 @@ -package com.cmx.wanhui.utils; +package com.cmx.wanhui.utils -import android.app.Activity; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Context; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.database.Cursor; -import android.graphics.Color; -import android.net.Uri; -import android.os.Build; -import android.os.Environment; -import android.os.StatFs; -import android.provider.MediaStore; -import android.util.Log; -import android.view.View; -import android.view.WindowManager; +import android.app.Activity +import android.content.Context +import android.graphics.Color +import android.os.Build +import android.os.Environment +import android.os.StatFs +import android.util.Log +import android.view.View +import android.view.WindowManager +import java.io.BufferedReader +import java.io.File +import java.io.FileReader +import java.io.IOException +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.security.NoSuchAlgorithmException +import java.util.Locale -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Locale; - -public class MyUtils { - private static final String TAG = "cmx_" + MyUtils.class.getSimpleName(); - public static void setNavigationStatusColor(Activity activity, int color) { - activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); - activity.getWindow().setNavigationBarColor(color); - activity.getWindow().setStatusBarColor(color); +object MyUtils { + private val TAG = "cmx_" + MyUtils::class.java.simpleName + fun setNavigationStatusColor(activity: Activity, color: Int) { + activity.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) + activity.window.navigationBarColor = color + activity.window.statusBarColor = color } - public static void setFullscreen(Activity activity, boolean isShowStatusBar, boolean isShowNavigationBar) { - int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; - + @JvmStatic + fun setFullscreen(activity: Activity, isShowStatusBar: Boolean, isShowNavigationBar: Boolean) { + var uiOptions = + View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY if (!isShowStatusBar) { - uiOptions |= View.SYSTEM_UI_FLAG_FULLSCREEN; + uiOptions = uiOptions or View.SYSTEM_UI_FLAG_FULLSCREEN } if (!isShowNavigationBar) { - uiOptions |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; + uiOptions = uiOptions or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION } - activity.getWindow().getDecorView().setSystemUiVisibility(uiOptions); - setNavigationStatusColor(activity, Color.TRANSPARENT); + activity.window.decorView.systemUiVisibility = uiOptions + setNavigationStatusColor(activity, Color.TRANSPARENT) } - public static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) { - View decor = activity.getWindow().getDecorView(); + @JvmStatic + fun setAndroidNativeLightStatusBar(activity: Activity, dark: Boolean) { + val decor = activity.window.decorView if (dark) { - decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); + decor.systemUiVisibility = + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { - decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + decor.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE } } - - private static String getVersionName(Activity activity) throws Exception { - PackageManager packageManager = activity.getPackageManager(); + @Throws(Exception::class) + private fun getVersionName(activity: Activity): String { + val packageManager = activity.packageManager // getPackageName()是你当前类的包名,0代表是获取版本信息 - PackageInfo packInfo = packageManager.getPackageInfo(activity.getPackageName(), 0); - String version = packInfo.versionName; - return version; + val packInfo = packageManager.getPackageInfo(activity.packageName, 0) + return packInfo.versionName } - public static void getDeviceInfo(Activity activity) throws Exception { - String model = android.os.Build.MODEL; - String carrier = android.os.Build.MANUFACTURER; - String version = getVersionName(activity); - String lang = getSystemLanguage(); - String brand = getPhoneBrand(); - String releaseVersion = getVersionRelease(); - int sdkVersion = getSdkVersion(); - Log.e(TAG, "model=" + model + ", carrier=" + carrier + ", version=" + version + ", lang=" + lang + ", brand=" + brand + ", releaseVersion=" + releaseVersion + ",sdk version=" + sdkVersion); + @Throws(Exception::class) + fun getDeviceInfo(activity: Activity) { + val model = Build.MODEL + val carrier = Build.MANUFACTURER + val version = getVersionName(activity) + val lang = systemLanguage + val brand = phoneBrand + val releaseVersion = versionRelease + val sdkVersion = sdkVersion + Log.e( + TAG, + "model=$model, carrier=$carrier, version=$version, lang=$lang, brand=$brand, releaseVersion=$releaseVersion,sdk version=$sdkVersion" + ) } - public static String getSystemLanguage() { - return Locale.getDefault().getLanguage(); - } + val systemLanguage: String + get() = Locale.getDefault().language + val systemLanguageList: Array + get() = Locale.getAvailableLocales() + val phoneBrand: String + get() = Build.BRAND + val versionRelease: String + get() = Build.VERSION.RELEASE + val sdkVersion: Int + get() = Build.VERSION.SDK_INT//8.0-//8.0+ - public static Locale[] getSystemLanguageList() { - return Locale.getAvailableLocales(); - } - - public static String getPhoneBrand() { - return Build.BRAND; - } - - public static String getVersionRelease() { - return Build.VERSION.RELEASE; - } - - public static int getSdkVersion() { - return Build.VERSION.SDK_INT; - } - - - public static String getSerialNum() { - String serial = "unknown"; - try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {//9.0+ - serial = Build.getSerial(); - } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {//8.0+ - serial = Build.SERIAL; - } else {//8.0- - Class c = Class.forName("android.os.SystemProperties"); - Method get = c.getMethod("get", String.class); - serial = (String) get.invoke(c, "ro.serialno"); + //9.0+ + val serialNum: String? + get() { + var serial: String? = "unknown" + try { + serial = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { //9.0+ + Build.getSerial() + } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) { //8.0+ + Build.SERIAL + } else { //8.0- + val c = Class.forName("android.os.SystemProperties") + val get = c.getMethod("get", String::class.java) + get.invoke(c, "ro.serialno") as String + } + } catch (e: Exception) { + Log.e("序列号》》", e.toString()) + e.printStackTrace() } - } catch (Exception e) { - Log.e("序列号》》", e.toString()); - e.printStackTrace(); + Log.e("序列号》》", serial!!) + return serial } - Log.e("序列号》》", serial); - return serial; + fun createTempImageFile(context: Context?): File? { + val destFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + destFolder.mkdirs() + val dateTimeString = System.currentTimeMillis().toString() + "" + var imageFile: File? = null + imageFile = try { + File.createTempFile("$dateTimeString-", ".jpg", destFolder) + } catch (e: IOException) { + Log.e("文件失败>>>", e.toString()) + throw RuntimeException(e) + } + return imageFile } - public static File createTempImageFile(Context context) { - File destFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); - destFolder.mkdirs(); - String dateTimeString = System.currentTimeMillis() + ""; - File imageFile = null; - try { - imageFile = File.createTempFile(dateTimeString + "-", ".jpg", destFolder); - } catch (IOException e) { - Log.e("文件失败>>>", e.toString()); - throw new RuntimeException(e); - } - - - return imageFile; - } - - - public static String getTotalRam() { - String path = "/proc/meminfo"; - String ramMemorySize = null; - int totalRam = 0; - try { - FileReader fileReader = new FileReader(path); - BufferedReader br = new BufferedReader(fileReader, 4096); - ramMemorySize = br.readLine().split("\\s+")[1]; - br.close(); - } catch (Exception e) { - e.printStackTrace(); - } - if (ramMemorySize != null) { - totalRam = (int) Math.ceil((Float.valueOf(Float.parseFloat(ramMemorySize) / (1024 * 1024)).doubleValue())); - } - - return totalRam + ""; - } - - public static String getTotalRom() { - File dataDir = Environment.getDataDirectory(); - StatFs stat = new StatFs(dataDir.getPath()); - long blockSize = stat.getBlockSizeLong(); - long totalBlocks = stat.getBlockCountLong(); - long size = totalBlocks * blockSize; - long GB = 1024 * 1024 * 1024; - final long[] deviceRomMemoryMap = {2 * GB, 4 * GB, 8 * GB, 16 * GB, 32 * GB, 64 * GB, 128 * GB, 256 * GB, 512 * GB, 1024 * GB, 2048 * GB}; - String[] displayRomSize = {"2GB", "4GB", "8GB", "16GB", "32GB", "64GB", "128GB", "256GB", "512GB", "1024GB", "2048GB"}; - int i; - for (i = 0; i < deviceRomMemoryMap.length; i++) { - if (size <= deviceRomMemoryMap[i]) { - break; + val totalRam: String + get() { + val path = "/proc/meminfo" + var ramMemorySize: String? = null + var totalRam = 0 + try { + val fileReader = FileReader(path) + val br = BufferedReader(fileReader, 4096) + ramMemorySize = br.readLine().split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1] + br.close() + } catch (e: Exception) { + e.printStackTrace() } - if (i == deviceRomMemoryMap.length) { - i--; + if (ramMemorySize != null) { + totalRam = Math.ceil(java.lang.Float.valueOf(ramMemorySize.toFloat() / (1024 * 1024)).toDouble()).toInt() } + return totalRam.toString() + "" + } + val totalRom: String + get() { + val dataDir = Environment.getDataDirectory() + val stat = StatFs(dataDir.path) + val blockSize = stat.blockSizeLong + val totalBlocks = stat.blockCountLong + val size = totalBlocks * blockSize + val GB = (1024 * 1024 * 1024).toLong() + val deviceRomMemoryMap = + longArrayOf(2 * GB, 4 * GB, 8 * GB, 16 * GB, 32 * GB, 64 * GB, 128 * GB, 256 * GB, 512 * GB, 1024 * GB, 2048 * GB) + val displayRomSize = + arrayOf("2GB", "4GB", "8GB", "16GB", "32GB", "64GB", "128GB", "256GB", "512GB", "1024GB", "2048GB") + var i: Int + i = 0 + while (i < deviceRomMemoryMap.size) { + if (size <= deviceRomMemoryMap[i]) { + break + } + if (i == deviceRomMemoryMap.size) { + i-- + } + i++ + } + return displayRomSize[i].replace("GB", "") } - return displayRomSize[i].replace("GB", ""); - } /** * sha256加密 @@ -182,39 +171,36 @@ public class MyUtils { * @param str 要加密的字符串 * @return 加密后的字符串 */ - public static String getSha256Str(String str) { - MessageDigest messageDigest; - String encodeStr = ""; + fun getSha256Str(str: String): String { + val messageDigest: MessageDigest + var encodeStr = "" try { - messageDigest = MessageDigest.getInstance("SHA-256"); - messageDigest.update(str.getBytes(StandardCharsets.UTF_8)); - encodeStr = byte2Hex(messageDigest.digest()); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); + messageDigest = MessageDigest.getInstance("SHA-256") + messageDigest.update(str.toByteArray(StandardCharsets.UTF_8)) + encodeStr = byte2Hex(messageDigest.digest()) + } catch (e: NoSuchAlgorithmException) { + e.printStackTrace() } - return encodeStr; + return encodeStr } - /** * sha256加密 将byte转为16进制 * * @param bytes 字节码 * @return 加密后的字符串 */ - private static String byte2Hex(byte[] bytes) { - StringBuilder stringBuilder = new StringBuilder(); - String temp; - for (byte aByte : bytes) { - temp = Integer.toHexString(aByte & 0xFF); - if (temp.length() == 1) { + private fun byte2Hex(bytes: ByteArray): String { + val stringBuilder = StringBuilder() + var temp: String + for (aByte in bytes) { + temp = Integer.toHexString(aByte.toInt() and 0xFF) + if (temp.length == 1) { //1得到一位的进行补0操作 - stringBuilder.append("0"); + stringBuilder.append("0") } - stringBuilder.append(temp); + stringBuilder.append(temp) } - return stringBuilder.toString(); + return stringBuilder.toString() } - - -} +} \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/utils/SpUtils.kt b/app/src/main/java/com/cmx/wanhui/utils/SpUtils.kt index 1381f55..47c4800 100644 --- a/app/src/main/java/com/cmx/wanhui/utils/SpUtils.kt +++ b/app/src/main/java/com/cmx/wanhui/utils/SpUtils.kt @@ -1,24 +1,20 @@ -package com.cmx.wanhui.utils; +package com.cmx.wanhui.utils -import android.app.Activity; -import android.content.Context; -import android.content.SharedPreferences; -import android.view.WindowManager; +import android.content.Context -public class SpUtils { - private static final String SP_NAME = "SP_USER_DATA"; - - - public static void putString(Context context, String key, String val) { - SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = sp.edit(); - editor.putString(key, val); - editor.commit(); +object SpUtils { + private const val SP_NAME = "SP_USER_DATA" + @JvmStatic + fun putString(context: Context, key: String?, `val`: String?) { + val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE) + val editor = sp.edit() + editor.putString(key, `val`) + editor.commit() } - public static String getString(Context context, String key) { - SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); - return sp.getString(key, ""); + @JvmStatic + fun getString(context: Context, key: String?): String? { + val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE) + return sp.getString(key, "") } - -} +} \ No newline at end of file diff --git a/app/src/main/java/com/cmx/wanhui/utils/StaticFinalData.kt b/app/src/main/java/com/cmx/wanhui/utils/StaticFinalData.kt index 2ddd5c6..e58f1ec 100644 --- a/app/src/main/java/com/cmx/wanhui/utils/StaticFinalData.kt +++ b/app/src/main/java/com/cmx/wanhui/utils/StaticFinalData.kt @@ -1,8 +1,8 @@ -package com.cmx.wanhui.utils; +package com.cmx.wanhui.utils -public class StaticFinalData { - public static final String LOGOUT = "LOGOUT"; - public static final String UPLOAD_FACE = "UPLOAD_FACE"; - public static final String UPLOAD_FACE_OVER = "UPLOAD_FACE_OVER"; - public static final String CHANGE_TAB = "CHANGE_TAB"; -} +object StaticFinalData { + const val LOGOUT = "LOGOUT" + const val UPLOAD_FACE = "UPLOAD_FACE" + const val UPLOAD_FACE_OVER = "UPLOAD_FACE_OVER" + const val CHANGE_TAB = "CHANGE_TAB" +} \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e0e1335..8eca043 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -51,5 +51,7 @@ If you have any questions or suggestions about our Terms and Conditions, do not This Terms and Conditions page was generated by App Privacy Policy Generator + + Hello blank fragment \ No newline at end of file