Compare commits

...

2 Commits

Author SHA1 Message Date
lijie 9d36282b14 同步 2023-08-07 11:46:02 +08:00
lijie 05a7d6bdff Rename .java to .kt 2023-08-07 11:46:02 +08:00
44 changed files with 900 additions and 1401 deletions

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetDropDown">
<runningDeviceTargetSelectedWithDropDown>
<Target>
<type value="RUNNING_DEVICE_TARGET" />
<deviceKey>
<Key>
<type value="SERIAL_NUMBER" />
<value value="R5CT20CJY5V" />
</Key>
</deviceKey>
</Target>
</runningDeviceTargetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2023-08-07T03:40:58.879605600Z" />
</component>
</project>

View File

@ -1,75 +0,0 @@
package com.cmx.hydrology.activity;
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.hydrology.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);
}
public void showDialog() {
if (!mBaseLoadingDialog.isShowing()) {
mBaseLoadingDialog.show();
}
}
public void 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;
}
@Override
public void onPageFinished(WebView view, String url) {
disDialog();
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
disDialog();
}
}
);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mApolloBinder != null) {
mApolloBinder.unbind();
}
}
}

View File

@ -0,0 +1,76 @@
package com.cmx.hydrology.activity
import android.graphics.Bitmap
import android.os.Bundle
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import com.cmx.hydrology.utils.AndroidtoJs
import com.cmx.hydrology.view.BaseLoadingDialog
import com.lsxiao.apollo.core.Apollo
import com.lsxiao.apollo.core.contract.ApolloBinder
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)
}
fun showDialog() {
if (!mBaseLoadingDialog!!.isShowing) {
mBaseLoadingDialog!!.show()
}
}
fun disDialog() {
if (mBaseLoadingDialog!!.isShowing) {
mBaseLoadingDialog!!.dismiss()
}
}
fun setWeb(mWebView: WebView) {
val webSettings = mWebView!!.settings
webSettings.javaScriptEnabled = true
webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
webSettings.domStorageEnabled = true
mWebView!!.addJavascriptInterface(AndroidtoJs(), "AndroidtoJs")
mWebView.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
showDialog()
}
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 onDestroy() {
super.onDestroy()
if (mApolloBinder != null) {
mApolloBinder!!.unbind()
}
}
companion object {
private const val TAG = "BaseActivity"
}
}

View File

@ -60,8 +60,8 @@ class LoginActivity : BaseActivity() {
LoginBean.username = binding!!.edtUsername.text.toString().trim { it <= ' ' }
LoginBean.password = binding!!.edtPassword.text.toString().trim { it <= ' ' }
val call = RetrofitAPIManager.provideClientApi().login(LoginBean)
call.enqueue(object : Callback<LoginRes> {
override fun onResponse(call: Call<LoginRes>, response: Response<LoginRes>) {
call!!.enqueue(object : Callback<LoginRes?> {
override fun onResponse(call: Call<LoginRes?>, response: Response<LoginRes?>) {
disDialog()
if (response.isSuccessful && response.body()!!.code == 0) {
SpUtils.putString(this@LoginActivity, "token", response.body()!!.access_token)
@ -69,11 +69,11 @@ class LoginActivity : BaseActivity() {
startActivity(intent)
finish()
} else {
Toasty.error(this@LoginActivity, response.body()!!.message).show()
Toasty.error(this@LoginActivity, response.body()!!.message!!).show()
}
}
override fun onFailure(call: Call<LoginRes>, t: Throwable) {
override fun onFailure(call: Call<LoginRes?>, t: Throwable) {
disDialog()
Toasty.info(this@LoginActivity, "登录失败").show()
}

View File

@ -1,40 +0,0 @@
package com.cmx.hydrology.activity;
import android.app.Application;
import android.content.Context;
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);
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
}
public static MyApplication getmInstance() {
return mInstance;
}
public static String getmToken() {
return mToken;
}
public static void setmToken(String mToken) {
MyApplication.mToken = mToken;
}
}

View File

@ -0,0 +1,35 @@
package com.cmx.hydrology.activity
import android.app.Application
import android.content.Context
import com.lsxiao.apollo.core.Apollo
import io.reactivex.android.schedulers.AndroidSchedulers
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
mInstance = this
Apollo.init(AndroidSchedulers.mainThread(), this)
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
}
companion object {
private var mInstance: MyApplication? = null
private var mToken: String? = null
@JvmStatic
fun getmInstance(): MyApplication? {
return mInstance
}
fun getmToken(): String? {
return mToken
}
fun setmToken(mToken: String?) {
Companion.mToken = mToken
}
}
}

View File

@ -1,179 +0,0 @@
package com.cmx.hydrology.activity;
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.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import androidx.annotation.Nullable;
import com.cmx.hydrology.databinding.ActivityWebBinding;
import com.cmx.hydrology.utils.AndroidtoJs;
import com.cmx.hydrology.utils.L;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class WebActivity extends BaseActivity {
private WebView mWebView;
private ActivityWebBinding binding;
private String url;
public static final int REQUEST_CODE_LIVENESS = 209;
public static final int TRUST_LEVEL = 50;
private ValueCallback<Uri[]> mUploadMessage;
private String mCameraPhotoPath = null;
private long size = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityWebBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
url = getIntent().getStringExtra("url");
// MyUtils.setFullscreen(this, true, true);//影响键盘 模式 页面遮挡
// MyUtils.setAndroidNativeLightStatusBar(this, true);//影响键盘 模式 页面遮挡
mWebView = binding.wvRegister;
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webSettings.setDomStorageEnabled(true);
mWebView.addJavascriptInterface(new AndroidtoJs(), "AndroidtoJs");
mWebView.loadUrl(url);
showDialog();
setWeb(mWebView);
mWebView.setWebChromeClient(new PQChromeClient());
}
// @Receive(Events.JS_OPEN_CLOSE_WEB)
// public void fin() {
// finish();
// }
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101 && mUploadMessage != null) {
try {
String file_path = mCameraPhotoPath.replace("file:", "");
File file = new File(file_path);
size = file.length();
if (!(data != null || size > 0)) {
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
return;
}
if (data != null || mCameraPhotoPath != null) {
Integer count = 1;
ClipData images = null;
try {
images = data.getClipData();
} catch (Exception e) {
Log.e("Error11!", e.getLocalizedMessage());
}
if (images == null && data != null && data.getDataString() != null) {
count = data.getDataString().length();
} else if (images != null) {
count = images.getItemCount();
}
Uri[] results = new Uri[count];
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (size != 0) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else if (data.getClipData() == null) {
results = new Uri[]{Uri.parse(data.getDataString())};
} else {
for (int i = 0; i < images.getItemCount(); i++) {
results[i] = images.getItemAt(i).getUri();
}
}
}
mUploadMessage.onReceiveValue(results);
mUploadMessage = null;
}
} catch (Exception e) {
Log.e("Error22!", "Error while opening image file" + e.getLocalizedMessage());
}
}
}
public class PQChromeClient extends WebChromeClient {
// For Android 5.0+
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
L.e("点击》》", "11");
// Double check that we don't have any existing callbacks
if (mUploadMessage != null) {
L.e("点击》》", "22");
mUploadMessage.onReceiveValue(null);
}
mUploadMessage = filePath;
Log.e("FileCooserParams => ", filePath.toString());
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
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));
} else {
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"), 101);
return true;
}
}
private File createImageFile() throws IOException {
// 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;
}
}

View File

@ -0,0 +1,50 @@
package com.cmx.hydrology.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.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import com.cmx.hydrology.constant.Events
import com.cmx.hydrology.databinding.ActivityWebBinding
import com.cmx.hydrology.utils.AndroidtoJs
import com.cmx.hydrology.utils.L
import com.lsxiao.apollo.core.annotations.Receive
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
class WebActivity : BaseActivity() {
private var mWebView: WebView? = null
private var binding: ActivityWebBinding? = null
private var url: String? = null
private var mUploadMessage: ValueCallback<Array<Uri>>? = null
private var mCameraPhotoPath: String? = null
private var size: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityWebBinding.inflate(layoutInflater)
setContentView(binding!!.root)
url = intent.getStringExtra("url")
mWebView = binding!!.wvRegister
setWeb(mWebView!!)
mWebView!!.loadUrl(url!!)
}
@Receive(Events.JS_OPEN_CLOSE_WEB)
fun fin() {
finish();
}
companion object {
}
}

View File

@ -1,22 +0,0 @@
package com.cmx.hydrology.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;
}
}

View File

@ -0,0 +1,6 @@
package com.cmx.hydrology.model
class LoginBean {
var username: String? = null
var password: String? = null
}

View File

@ -1,42 +0,0 @@
package com.cmx.hydrology.model;
public class LoginRes {
/**
* code : 0
* message :
* access_token : 1914936f8c87fddd11836ebebb65317bb7f57506
*/
private int code;
private String message;
private String access_token;
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;
}
}

View File

@ -0,0 +1,12 @@
package com.cmx.hydrology.model
class LoginRes {
/**
* code : 0
* message : 登录成功
* access_token : 1914936f8c87fddd11836ebebb65317bb7f57506
*/
var code = 0
var message: String? = null
var access_token: String? = null
}

View File

@ -1,47 +0,0 @@
package com.cmx.hydrology.retrofit;
import com.google.gson.reflect.TypeToken;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
public class ApiRequtest<T> {
private static final String TAG = ApiRequtest.class.getSimpleName();
private TypeToken<T> mResultType;
public ApiRequtest (Call<ResponseBody> call, TypeToken<T> resultType, final ApiResponse.Listener<ApiResult<T>> listener, final ApiResponse.ErrorListener errorListener){
mResultType = resultType;
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
ResponseBody responseBody = response.body();
if(responseBody != null){
String jsonString = response.body().string();
final ApiResult<T> result = new ApiResult<>(new JSONObject(jsonString), mResultType);
listener.onResponse(result);
}
}catch (IOException e){
}catch (JSONException e) {
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
errorListener.onErrorResponse(t);
}
});
}
}

View File

@ -0,0 +1,42 @@
package com.cmx.hydrology.retrofit
import com.google.gson.reflect.TypeToken
import okhttp3.ResponseBody
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.IOException
class ApiRequtest<T>(
call: Call<ResponseBody?>,
private val mResultType: TypeToken<T>,
listener: ApiResponse.Listener<ApiResult<T>?>,
errorListener: ApiResponse.ErrorListener
) {
init {
call.enqueue(object : Callback<ResponseBody?> {
override fun onResponse(call: Call<ResponseBody?>, response: Response<ResponseBody?>) {
try {
val responseBody = response.body()
if (responseBody != null) {
val jsonString = response.body()!!.string()
val result = ApiResult(JSONObject(jsonString), mResultType)
listener.onResponse(result)
}
} catch (e: IOException) {
} catch (e: JSONException) {
}
}
override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {
errorListener.onErrorResponse(t)
}
})
}
companion object {
private val TAG = ApiRequtest::class.java.simpleName
}
}

View File

@ -1,19 +0,0 @@
package com.cmx.hydrology.retrofit;
public class ApiResponse<T> {
/**
* network request error response
*/
public interface ErrorListener {
void onErrorResponse(Throwable requestError);
}
/**
* network request success response result
* @param <T> data result
*/
public interface Listener<T> {
void onResponse(T result);
}
}

View File

@ -0,0 +1,18 @@
package com.cmx.hydrology.retrofit
class ApiResponse<T> {
/**
* network request error response
*/
interface ErrorListener {
fun onErrorResponse(requestError: Throwable?)
}
/**
* network request success response result
* @param <T> data result
</T> */
interface Listener<T> {
fun onResponse(result: T)
}
}

View File

@ -1,104 +0,0 @@
package com.cmx.hydrology.retrofit;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
/**
*
*/
public class ApiResult<T> {
private final static String TAG = ApiResult.class.getSimpleName();
public static final int OK = 0;
public Boolean success = true;
private Integer code = OK;
private String msg="";
private T result;
private String msgJson;
private static Gson gson = new Gson();
public ApiResult() {
super();
// TODO Auto-generated constructor stub
}
public ApiResult(JSONObject jsonObject, TypeToken<T> typeToken) {
super();
try{
if (jsonObject.has("errcode")){
code = jsonObject.getInt("errcode");
if (code != OK) {
if (jsonObject.has("errmsg")) {
msg = jsonObject.getString("errmsg");
}
success = false;
}
}else{
}
if (code == OK){
try {
result = gson.fromJson(jsonObject.toString(), typeToken.getType());
}catch (Exception ex){
}
}
}catch (Exception e) {
// TODO: handle exception
}
}
private T testDefault(String msg){
Gson gson = new Gson();
result = gson.fromJson(msg,new TypeToken<T>(){}.getType());
return result;
}
private T test(String msg, TypeToken<T> typeToken){
Gson gson = new Gson();
result = gson.fromJson(msg,typeToken.getType());
return result;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMsgJson() {
return msgJson;
}
}

View File

@ -0,0 +1,65 @@
package com.cmx.hydrology.retrofit
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.json.JSONObject
/**
*
*/
class ApiResult<T> {
var success = true
var code = OK
var msg = ""
var result: T? = null
private set
val msgJson: String? = null
constructor() : super() { // TODO Auto-generated constructor stub
}
constructor(jsonObject: JSONObject, typeToken: TypeToken<T>) : super() {
try {
if (jsonObject.has("errcode")) {
code = jsonObject.getInt("errcode")
if (code != OK) {
if (jsonObject.has("errmsg")) {
msg = jsonObject.getString("errmsg")
}
success = false
}
} else {
}
if (code == OK) {
try {
result = gson.fromJson(jsonObject.toString(), typeToken.type)
} catch (ex: Exception) {
}
}
} catch (e: Exception) {
// TODO: handle exception
}
}
private fun testDefault(msg: String): T? {
val gson = Gson()
result = gson.fromJson(msg, object : TypeToken<T>() {}.type)
return result
}
private fun test(msg: String, typeToken: TypeToken<T>): T? {
val gson = Gson()
result = gson.fromJson(msg, typeToken.type)
return result
}
fun setResult(result: T) {
this.result = result
}
companion object {
private val TAG = ApiResult::class.java.simpleName
const val OK = 0
private val gson = Gson()
}
}

View File

@ -1,22 +0,0 @@
package com.cmx.hydrology.retrofit;
import com.cmx.hydrology.model.LoginBean;
import com.cmx.hydrology.model.LoginRes;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
/**
* Created by
*/
public interface ApiService {
/**
*
*
* @param body
* @return
*/
@POST("/login")
Call<LoginRes> login(@Body LoginBean body);
}

View File

@ -0,0 +1,21 @@
package com.cmx.hydrology.retrofit
import com.cmx.hydrology.model.LoginBean
import com.cmx.hydrology.model.LoginRes
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST
/**
* Created by
*/
interface ApiService {
/**
* 登录
*
* @param body
* @return
*/
@POST("/login")
fun login(@Body body: LoginBean?): Call<LoginRes?>?
}

View File

@ -1,71 +0,0 @@
package com.cmx.hydrology.retrofit;
import static com.cmx.hydrology.constant.Events.SERVER_URL;
import android.util.Log;
import com.cmx.hydrology.activity.MyApplication;
import com.cmx.hydrology.utils.SpUtils;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by TTLock on 2018/9/5.
*/
public class RetrofitAPIManager {
public static ApiService provideClientApi() {
Retrofit retrofit = new Retrofit.Builder().client(genericClient()).baseUrl(SERVER_URL).addConverterFactory(GsonConverterFactory.create()).build();
return retrofit.create(ApiService.class);
}
public static OkHttpClient genericClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
// try {
// String text = URLDecoder.decode(message, "utf-8");
// Log.e("OKHttp-----", text);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
Log.e("OKHttp-----", message);
// }
}
});
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder().connectTimeout(35, TimeUnit.SECONDS).readTimeout(35, TimeUnit.SECONDS).writeTimeout(35, TimeUnit.SECONDS).addInterceptor(interceptor).addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder().header("token", SpUtils.getString(MyApplication.getmInstance(), "token"));
Request request = requestBuilder.build();
return chain.proceed(request);
}
}).build();
return httpClient;
}
public static <T> ApiRequtest enqueue(Call<ResponseBody> call, TypeToken<T> resultType, ApiResponse.Listener<ApiResult<T>> listener, ApiResponse.ErrorListener errorListener) {
ApiRequtest<T> request = new ApiRequtest<>(call, resultType, listener, errorListener);
return request;
}
}

View File

@ -0,0 +1,55 @@
package com.cmx.hydrology.retrofit
import android.util.Log
import com.cmx.hydrology.activity.MyApplication.Companion.getmInstance
import com.cmx.hydrology.constant.Events
import com.cmx.hydrology.utils.SpUtils
import com.google.gson.reflect.TypeToken
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
* Created by TTLock on 2018/9/5.
*/
object RetrofitAPIManager {
fun provideClientApi(): ApiService {
val retrofit = Retrofit.Builder().client(genericClient()).baseUrl(Events.SERVER_URL)
.addConverterFactory(GsonConverterFactory.create()).build()
return retrofit.create(ApiService::class.java)
}
fun genericClient(): OkHttpClient {
val interceptor = HttpLoggingInterceptor { message ->
// try {
// String text = URLDecoder.decode(message, "utf-8");
// Log.e("OKHttp-----", text);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
Log.e("OKHttp-----", message)
// }
}
interceptor.level = HttpLoggingInterceptor.Level.BODY
return OkHttpClient.Builder().connectTimeout(35, TimeUnit.SECONDS).readTimeout(35, TimeUnit.SECONDS)
.writeTimeout(35, TimeUnit.SECONDS).addInterceptor(interceptor).addInterceptor { chain ->
val original = chain.request()
val requestBuilder =
original.newBuilder().header("token", SpUtils.getString(getmInstance()!!, "token"))
val request = requestBuilder.build()
chain.proceed(request)
}.build()
}
fun <T> enqueue(
call: Call<ResponseBody?>?,
resultType: TypeToken<T>?,
listener: ApiResponse.Listener<ApiResult<T>?>?,
errorListener: ApiResponse.ErrorListener?
): ApiRequtest<*> {
return ApiRequtest(call!!, resultType!!, listener!!, errorListener!!)
}
}

View File

@ -1,9 +0,0 @@
package com.cmx.hydrology.retrofit;
/**
* Created by Administrator on 2018/1/17 0017.
*/
public interface onRequestResponse {
void onResult(boolean success);
}

View File

@ -0,0 +1,8 @@
package com.cmx.hydrology.retrofit
/**
* Created by Administrator on 2018/1/17 0017.
*/
interface onRequestResponse {
fun onResult(success: Boolean)
}

View File

@ -1,9 +0,0 @@
package com.cmx.hydrology.retrofit;
/**
* Created by Administrator on 2018/1/17 0017.
*/
public interface onServerRequestCallBack {
void onResult(int resultCode);
}

View File

@ -0,0 +1,8 @@
package com.cmx.hydrology.retrofit
/**
* Created by Administrator on 2018/1/17 0017.
*/
interface onServerRequestCallBack {
fun onResult(resultCode: Int)
}

View File

@ -1,180 +0,0 @@
package com.cmx.hydrology.ui;
import static com.cmx.hydrology.constant.Events.WEB_HOME_URL;
import static com.cmx.hydrology.constant.Events.WEB_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.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.cmx.hydrology.databinding.FragmentHomeBinding;
import com.cmx.hydrology.utils.AndroidtoJs;
import com.cmx.hydrology.utils.MyUtils;
import com.cmx.hydrology.view.BaseLoadingDialog;
import com.lsxiao.apollo.core.Apollo;
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 BaseFragment {
private FragmentHomeBinding binding;
private WebView mWebView;
private ValueCallback<Uri[]> mUploadMessage;
private String mCameraPhotoPath = null;
private long size = 0;
private static final int INPUT_FILE_REQUEST_CODE = 1;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
mWebView = binding.wvHome;
setWebView(mWebView);
mWebView.loadUrl(WEB_HOME_URL);
mWebView.setWebChromeClient(new PQChromeClient());
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
public class PQChromeClient extends WebChromeClient {
// For Android 5.0+
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mUploadMessage != 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) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
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));
} else {
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;
}
}
private File createImageFile() throws IOException {
// 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;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
try {
String file_path = mCameraPhotoPath.replace("file:", "");
File file = new File(file_path);
size = file.length();
if (data != null || mCameraPhotoPath != null) {
Integer count = 1;
ClipData images = null;
try {
images = data.getClipData();
} catch (Exception e) {
Log.e("Error!", e.getLocalizedMessage());
}
if (images == null && data != null && data.getDataString() != null) {
count = data.getDataString().length();
} else if (images != null) {
count = images.getItemCount();
}
Uri[] results = new Uri[count];
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (size != 0) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else if (data.getClipData() == null) {
results = new Uri[]{Uri.parse(data.getDataString())};
} else {
for (int i = 0; i < images.getItemCount(); i++) {
results[i] = images.getItemAt(i).getUri();
}
}
}
mUploadMessage.onReceiveValue(results);
mUploadMessage = null;
}
} catch (Exception e) {
Log.e("Error!", "Error while opening image file" + e.getLocalizedMessage());
}
}
}

View File

@ -0,0 +1,48 @@
package com.cmx.hydrology.ui
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.hydrology.constant.Events
import com.cmx.hydrology.databinding.FragmentHomeBinding
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
class HomeFragment : BaseFragment() {
private var binding: FragmentHomeBinding? = null
private var mWebView: WebView? = null
private var mUploadMessage: ValueCallback<Array<Uri>>? = null
private var mCameraPhotoPath: String? = null
private var size: Long = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding!!.root
mWebView = binding!!.wvHome
setWebView(mWebView!!)
mWebView!!.loadUrl(Events.WEB_HOME_URL)
return root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
companion object {
private const val INPUT_FILE_REQUEST_CODE = 1
}
}

View File

@ -1,48 +0,0 @@
package com.cmx.hydrology.ui;
import static com.cmx.hydrology.constant.Events.WEB_MAP_URL;
import static com.cmx.hydrology.constant.Events.WEB_SERVER_URL;
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.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.cmx.hydrology.databinding.FragmentMapBinding;
import com.cmx.hydrology.utils.AndroidtoJs;
import com.cmx.hydrology.utils.MyUtils;
import com.cmx.hydrology.view.BaseLoadingDialog;
import com.lsxiao.apollo.core.Apollo;
import com.lsxiao.apollo.core.contract.ApolloBinder;
public class MapFragment extends BaseFragment {
private FragmentMapBinding binding;
private WebView mWebView;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentMapBinding.inflate(inflater, container, false);
View root = binding.getRoot();
mWebView = binding.wvMine;
setWebView(mWebView);
mWebView.loadUrl(WEB_MAP_URL);
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}

View File

@ -0,0 +1,27 @@
package com.cmx.hydrology.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import com.cmx.hydrology.constant.Events
import com.cmx.hydrology.databinding.FragmentMapBinding
class MapFragment : BaseFragment() {
private var binding: FragmentMapBinding? = null
private var mWebView: WebView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentMapBinding.inflate(inflater, container, false)
val root: View = binding!!.root
mWebView = binding!!.wvMine
setWebView(mWebView!!)
mWebView!!.loadUrl(Events.WEB_MAP_URL)
return root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
}

View File

@ -1,63 +0,0 @@
package com.cmx.hydrology.ui;
import static com.cmx.hydrology.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.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.cmx.hydrology.databinding.FragmentMsgBinding;
import com.cmx.hydrology.utils.AndroidtoJs;
import com.cmx.hydrology.utils.MyUtils;
import com.cmx.hydrology.view.BaseLoadingDialog;
import com.lsxiao.apollo.core.Apollo;
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 MsgFragment extends BaseFragment {
private FragmentMsgBinding binding;
private WebView mWebView;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentMsgBinding.inflate(inflater, container, false);
View root = binding.getRoot();
mWebView = binding.wvLoan;
setWebView(mWebView);
// mWebView.loadUrl(SERVER_URL + "/nigeria/?lang=English#/loans");
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}

View File

@ -0,0 +1,26 @@
package com.cmx.hydrology.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import com.cmx.hydrology.databinding.FragmentMsgBinding
class MsgFragment : BaseFragment() {
private var binding: FragmentMsgBinding? = null
private var mWebView: WebView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentMsgBinding.inflate(inflater, container, false)
val root: View = binding!!.root
mWebView = binding!!.wvLoan
setWebView(mWebView!!)
// mWebView.loadUrl(SERVER_URL + "/nigeria/?lang=English#/loans");
return root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
}

View File

@ -1,45 +0,0 @@
package com.cmx.hydrology.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.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.cmx.hydrology.databinding.FragmentMyBinding;
import com.cmx.hydrology.utils.AndroidtoJs;
import com.cmx.hydrology.utils.MyUtils;
import com.cmx.hydrology.view.BaseLoadingDialog;
import com.lsxiao.apollo.core.Apollo;
import com.lsxiao.apollo.core.contract.ApolloBinder;
public class MyFragment extends BaseFragment {
private FragmentMyBinding binding;
private WebView mWebView;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentMyBinding.inflate(inflater, container, false);
View root = binding.getRoot();
mWebView = binding.wvMine;
setWebView(mWebView);
// mWebView.loadUrl(SERVER_URL + "/nigeria/?lang=English#/my");
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}

View File

@ -0,0 +1,26 @@
package com.cmx.hydrology.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import com.cmx.hydrology.databinding.FragmentMyBinding
class MyFragment : BaseFragment() {
private var binding: FragmentMyBinding? = null
private var mWebView: WebView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentMyBinding.inflate(inflater, container, false)
val root: View = binding!!.root
mWebView = binding!!.wvMine
setWebView(mWebView!!)
// mWebView.loadUrl(SERVER_URL + "/nigeria/?lang=English#/my");
return root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
}

View File

@ -1,78 +0,0 @@
package com.cmx.hydrology.utils;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.webkit.JavascriptInterface;
import com.cmx.hydrology.activity.MyApplication;
import com.cmx.hydrology.constant.Events;
import com.lsxiao.apollo.core.Apollo;
public class AndroidtoJs {
private static final String TAG = "cmx_AndroidtoJs";
// 定义JS需要调用的方法
// 被JS调用的方法必须加入@JavascriptInterface注解
@JavascriptInterface
public String getAppToken() {
L.e("JS--", "getAppToken()");
return SpUtils.getString(MyApplication.getmInstance(), "token");
}
@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 = "未知";
}
Log.e(TAG, "getAppVersion=" + versionname);
return versionname;
}
@JavascriptInterface
public void existApp() {
L.e("JS--", "existApp()");
Apollo.emit(Events.JS_OPEN_LOGOUT);
}
@JavascriptInterface
public void showTab() {//tabbar显示
L.e("JS--", "showTab()");
Apollo.emit(Events.JS_OPEN_TABBAR_SHOW);
}
@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);
}
}

View File

@ -0,0 +1,76 @@
package com.cmx.hydrology.utils
import android.content.pm.PackageManager
import android.util.Log
import android.webkit.JavascriptInterface
import com.cmx.hydrology.activity.MyApplication.Companion.getmInstance
import com.cmx.hydrology.constant.Events
import com.lsxiao.apollo.core.Apollo
class AndroidtoJs {
// 定义JS需要调用的方法
// 被JS调用的方法必须加入@JavascriptInterface注解
@get:JavascriptInterface
val appToken: String?
get() {
L.e("JS--", "getAppToken()")
return SpUtils.getString(getmInstance()!!, "token")
}
//版本号
@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
fun showTab() { //tabbar显示
L.e("JS--", "showTab()")
Apollo.emit(Events.JS_OPEN_TABBAR_SHOW)
}
@JavascriptInterface
fun hideTab() { //tabbar隐藏
L.e("JS--", "hideTab()")
Apollo.emit(Events.JS_OPEN_TABBAR_HIDE)
}
@JavascriptInterface
fun openWeb(url: String) { //打开一个新的web界面
L.e("JS--", "openWeb()$url")
Apollo.emit(Events.JS_OPEN_OPEN_WEB, url)
}
@JavascriptInterface
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!!)
}
companion object {
private const val TAG = "cmx_AndroidtoJs"
}
}

View File

@ -1,92 +0,0 @@
package com.cmx.hydrology.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 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");
}
public static boolean isDebug = true;
private static String TAG = "LjTestLog";
public static String getTAG() {
return TAG;
}
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);
}
}

View File

@ -0,0 +1,49 @@
package com.cmx.hydrology.utils
import android.util.Log
class L private constructor() {
init {
throw UnsupportedOperationException("cannot be instantiated")
}
companion object {
var isDebug = true
var tAG = "LjTestLog"
fun setDebugMode(debug: Boolean) {
isDebug = debug
}
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!!)
}
fun e(tag: String?, msg: String?) {
if (isDebug) Log.e(tag, msg!!)
}
fun v(tag: String?, msg: String?) {
if (isDebug) Log.v(tag, msg!!)
}
}
}

View File

@ -1,220 +0,0 @@
package com.cmx.hydrology.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 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);
}
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;
if (!isShowStatusBar) {
uiOptions |= View.SYSTEM_UI_FLAG_FULLSCREEN;
}
if (!isShowNavigationBar) {
uiOptions |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
activity.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
setNavigationStatusColor(activity, Color.TRANSPARENT);
}
public static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
View decor = activity.getWindow().getDecorView();
if (dark) {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
} else {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
}
private static String getVersionName(Activity activity) throws Exception {
PackageManager packageManager = activity.getPackageManager();
// getPackageName()是你当前类的包名0代表是获取版本信息
PackageInfo packInfo = packageManager.getPackageInfo(activity.getPackageName(), 0);
String version = packInfo.versionName;
return version;
}
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);
}
public static String getSystemLanguage() {
return Locale.getDefault().getLanguage();
}
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");
}
} catch (Exception e) {
Log.e("序列号》》", e.toString());
e.printStackTrace();
}
Log.e("序列号》》", serial);
return serial;
}
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;
}
if (i == deviceRomMemoryMap.length) {
i--;
}
}
return displayRomSize[i].replace("GB", "");
}
/**
* sha256
*
* @param str
* @return
*/
public static String getSha256Str(String str) {
MessageDigest messageDigest;
String encodeStr = "";
try {
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
encodeStr = byte2Hex(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return encodeStr;
}
/**
* sha256 byte16
*
* @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) {
//1得到一位的进行补0操作
stringBuilder.append("0");
}
stringBuilder.append(temp);
}
return stringBuilder.toString();
}
}

View File

@ -0,0 +1,205 @@
package com.cmx.hydrology.utils
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
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
}
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 = uiOptions or View.SYSTEM_UI_FLAG_FULLSCREEN
}
if (!isShowNavigationBar) {
uiOptions = uiOptions or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
}
activity.window.decorView.systemUiVisibility = uiOptions
setNavigationStatusColor(activity, Color.TRANSPARENT)
}
fun setAndroidNativeLightStatusBar(activity: Activity, dark: Boolean) {
val decor = activity.window.decorView
if (dark) {
decor.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
} else {
decor.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
}
}
@Throws(Exception::class)
private fun getVersionName(activity: Activity): String {
val packageManager = activity.packageManager
// getPackageName()是你当前类的包名0代表是获取版本信息
val packInfo = packageManager.getPackageInfo(activity.packageName, 0)
return packInfo.versionName
}
@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"
)
}
val systemLanguage: String
get() = Locale.getDefault().language
val systemLanguageList: Array<Locale>
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+
//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()
}
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
}
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 (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", "")
}
/**
* sha256加密
*
* @param str 要加密的字符串
* @return 加密后的字符串
*/
fun getSha256Str(str: String): String {
val messageDigest: MessageDigest
var encodeStr = ""
try {
messageDigest = MessageDigest.getInstance("SHA-256")
messageDigest.update(str.toByteArray(StandardCharsets.UTF_8))
encodeStr = byte2Hex(messageDigest.digest())
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
}
return encodeStr
}
/**
* sha256加密 将byte转为16进制
*
* @param bytes 字节码
* @return 加密后的字符串
*/
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(temp)
}
return stringBuilder.toString()
}
}

View File

@ -1,24 +0,0 @@
package com.cmx.hydrology.utils;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.WindowManager;
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();
}
public static String getString(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(key, "");
}
}

View File

@ -0,0 +1,18 @@
package com.cmx.hydrology.utils
import android.content.Context
object SpUtils {
private const val SP_NAME = "SP_USER_DATA"
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()
}
fun getString(context: Context, key: String?): String? {
val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
return sp.getString(key, "")
}
}

View File

@ -1,8 +0,0 @@
package com.cmx.hydrology.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";
}

View File

@ -0,0 +1,8 @@
package com.cmx.hydrology.utils
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"
}