package com.fgkj.action;
|
|
import android.app.Activity;
|
import android.content.ComponentName;
|
import android.content.Context;
|
import android.content.Intent;
|
import android.os.Handler;
|
import android.os.Looper;
|
import android.os.SystemClock;
|
import android.util.Log;
|
import android.webkit.JavascriptInterface;
|
import android.webkit.WebView;
|
import android.widget.Toast;
|
|
|
import com.google.gson.Gson;
|
import com.serial.SerialPortFinder;
|
|
import java.util.List;
|
|
public class JsInterface {
|
public static final String TAG = "JsInterface";
|
|
public static final String JS_INTERFACE_NAME = "JSInterface";//JS调用类名
|
private WebView webView;
|
private Gson gson = new Gson();
|
|
private Context mContext;
|
private Activity activity;
|
|
public JsInterface(Context context, WebView webView, Activity activity) {
|
this.mContext = context;
|
this.webView = webView;
|
this.activity = activity;
|
|
}
|
|
@JavascriptInterface
|
public void hello(String content) {
|
Log.i("bqt", "JS 调用原生时是否发生在主线程:" + (Looper.myLooper() == Looper.getMainLooper()));//false
|
new Handler(Looper.getMainLooper()).post(() -> //WebView等UI操作必须在主线程中进行
|
Toast.makeText(mContext, "原生的hello方法被调用了:" + content, Toast.LENGTH_SHORT).show());
|
|
SystemClock.sleep(3000);//模拟耗时操作
|
|
String call = "javascript:javacalljs(" + System.currentTimeMillis() + ")";//格式很重要,大部分错误都是由于格式问题导致的
|
new Handler(Looper.getMainLooper()).post(() -> webView.loadUrl(call));//WebView等UI操作必须在主线程中进行
|
}
|
|
@JavascriptInterface
|
public void getAllRS485Names(){
|
Toast.makeText(this.mContext,"进入获取串口号",Toast.LENGTH_SHORT).show();
|
SerialPortFinder finder = new SerialPortFinder();
|
String[] b = new String[0];
|
try {
|
b = finder.getAllDevicesPath();
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
ServiceModel model = new ServiceModel();
|
model.data = b;
|
|
SendCallDataToJS("getAllRS485Names",model);
|
}
|
|
/**
|
* 打开网络共享与热点设置页面
|
*/
|
@JavascriptInterface
|
public void openAndroidWifiUI() {
|
Intent intent = new Intent();
|
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
//打开网络共享与热点设置页面
|
ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity");
|
intent.setComponent(comp);
|
mContext.startActivity(intent);
|
}
|
|
/**
|
* 返回数据给前台js
|
* @param funName
|
* @param model
|
*/
|
public void SendCallDataToJS(String funName,ServiceModel model){
|
String call = "javascript:"+funName+"calljs(" + gson.toJson(model) + ")";
|
new Handler(Looper.getMainLooper()).post(() -> webView.loadUrl(call));
|
}
|
|
}
|