我需要使用Cordova Android 5.1.0创建3个自定义Cordova WebView
。以前我通过修改/覆盖文件WebView
成功使用Cordova Android 2.7创建自定义platform/android/src/com/hello/helloapp.java
。以下是我之前的代码:
package com.hello.helloapp;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewClient;
import com.hello.helloapp.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class HelloApp extends Activity implements CordovaInterface {
int SCREEN_WIDTH;
int SCREEN_HEIGHT;
static String parentUrl;;
CordovaWebView view2;
CordovaWebView view1;
CordovaWebView view3;
static String htmlStr;
LinearLayout layout;
boolean connectionStatus;
private final ExecutorService threadPool = Executors.newCachedThreadPool();
@Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Config.init(this);
this.getScreenSize();
view1 = (CordovaWebView) findViewById(R.id.local_web_view);
view1.loadUrl("file:///android_asset/www/index.html");
view2 = (CordovaWebView) findViewById(R.id.external_web_view);
view2.loadUrl("http://google.com");
view2.requestFocus(WebView.FOCUS_DOWN);
view2.setWebViewClient(new MyWebViewClient(this, view2));
view3 = (CordovaWebView) findViewById(R.id.articles_web_view);
view3.loadUrl("file:///android_asset/www/articles.html");
view2.addJavascriptInterface(this, "GetHTML");
layout = (LinearLayout) findViewById(R.id.progressBar);
if (!isTabletDevice(this)) {
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (isAirplaneModeOn(this)) {
connectionStatus = false;
} else if (isNetworkOnline()) {
connectionStatus = true;
} else
connectionStatus = false;
System.out.println(connectionStatus);
if (!connectionStatus) {
view2.setVisibility(View.GONE);
view3.loadUrl("file:///android_asset/www/articles.html");
view3.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isNetworkOnline() {
boolean status = false;
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
NetworkInfo netInfo1 = cm.getNetworkInfo(1);
if ((netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED)
|| (netInfo1 != null && netInfo1.getState() == NetworkInfo.State.CONNECTED)) {
status = true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
System.out.println(status);
return status;
}
public static boolean isTabletDevice(Context activityContext) {
// Verifies if the Generalized Size of the device is XLARGE to be
// considered a Tablet
boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
// If XLarge, checks if the Generalized Density is at least MDPI
// (160dpi)
if (xlarge) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
// DENSITY_TV=213, DENSITY_XHIGH=320
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
// Yes, this is a tablet!
return true;
}
}
// No, this is not a tablet!
return false;
}
@SuppressWarnings("deprecation")
private static boolean isAirplaneModeOn(Context context)
throws SettingNotFoundException {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
@Override
public Activity getActivity() {
return this;
}
@Override
public ExecutorService getThreadPool() {
return threadPool;
}
public void getScreenSize() {
Display display = getWindowManager().getDefaultDisplay();
SCREEN_WIDTH = display.getWidth();
SCREEN_HEIGHT = display.getHeight();
}
public class MyWebViewClient extends CordovaWebViewClient {
private CordovaInterface cordova;
public MyWebViewClient(CordovaInterface ctx, CordovaWebView app) {
super(ctx, app);
this.cordova = ctx;
}
@Override
public void onReceivedError(WebView arg0, int arg1, String arg2,
String arg3) {
arg0.loadUrl("javascript:navigator.notification.alert(\"Sorry,the network is not available.\",\"null\");");
}
public boolean shouldOverrideUrlLoading(final WebView view, String url) {
connectionStatus = isNetworkOnline();
System.out.println(connectionStatus);
if (connectionStatus) {
System.out.println("---------shouldoverride-------" + url);
if (url.contains(".pdf")&& !url.contains("originUrl")) {
System.out.println(HelloApp.htmlStr);
view1.loadUrl("javascript:downloadFile(\"" + url + "\",\""
+ HelloApp.htmlStr + "\",\"" + HelloApp.parentUrl
+ "\");");
return false;
} else if (url.contains("search?")
&& HelloApp.parentUrl
.equalsIgnoreCase("http://google.com/")) {
System.out.println("parenturl");
url = url.concat("&showAll=false");
view2.loadUrl(url);
return false;
} else {
return false;
}
} else {
view1.loadUrl("javascript:navigator.notification.alert(\"Sorry,the network is not available.\",\"null\");");
return true;
}
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layout.setVisibility(View.VISIBLE);
if (url.contains(".pdf")) {
}else {
HelloApp.parentUrl = url;
if (view2.canGoBack() && view2.canGoForward()) {
view1.loadUrl("javascript:callBackFun(\"F_1B_1\")");
} else if (view2.canGoForward()) {
view1.loadUrl("javascript:callBackFun(\"F_1\")");
} else if (view2.canGoBack()) {
view1.loadUrl("javascript:callBackFun(\"B_1\")");
}
}
super.onPageStarted(view, url, favicon);
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains(".pdf")) {
} else {
System.out.println("----------------" + url);
view2.loadUrl("javascript: GetHTML.getHtml(document.body.innerHTML);");
view2.loadUrl("javascript: $(\".content-pricing\").hide()");
view2.loadUrl("javascript: $(\"a[href*='mailto']\").removeAttr('href');");
System.out.println("REMOVE------------------------>>>");
view2.loadUrl("javascript:$('head').append('<style>#coverImageUrl, .content-pricing, .price-disclaimer {display : none;}</style>')");
layout.setVisibility(View.INVISIBLE);
}
}
}
public Object onMessage(String arg0, Object arg1) {
return null;
}
@Override
public void setActivityResultCallback(CordovaPlugin arg0) {
}
@Override
public void startActivityForResult(CordovaPlugin arg0, Intent arg1, int arg2) {
}
@JavascriptInterface
public void getHtml(String html) {
this.htmlStr = html.replace("\"", "\'").replaceAll("\n", "").replaceAll("%22", "\'").trim();
}
}
现在Cordova有很多更新,他们还会更新CordovaWebView
代码。将Cordova Android版本从2.7更新到5.1.0后,应用程序崩溃了。我尝试使用SystemWebView
代替CordovaWebView
,但由于SystemWebView
中缺少某些方法,我仍然会收到错误和崩溃。
请帮助我如何在Cordova 5.1.0中更新以前的WebView
代码或创建新的多个WebView
。
谢谢!
答案 0 :(得分:0)
这就是我在现有项目中实现新Cordova库的方法。
public class MyWebViewFragment extends Fragment{
private Activity mActivity;
private SystemWebView syswvPhoneWebview;
private CordovaWebView wvPhoneWebview;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (Activity) context;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (mView == null) {
mView = inflater.inflate(R.layout.fragment_web_view, null);
setLayoutViews(mView);
}
return mView;
}
private void setLayoutViews(View mView) {
syswvPhoneWebview = (SystemWebView) mView.findViewById(R.id.wvPhoneWebview);
wvPhoneWebview = new CordovaWebViewImpl(new SystemWebViewEngine(syswvPhoneWebview));
wvPhoneWebview.init((CordovaInterface) getParentFragment(), parser.getPluginEntries(), parser.getPreferences());
syswvPhoneWebview.setWebContentsDebuggingEnabled(true);
syswvPhoneWebview.getSettings().setLoadsImagesAutomatically(true);
syswvPhoneWebview.getSettings().setJavaScriptEnabled(true);
syswvPhoneWebview.getSettings().setDomStorageEnabled(true);
syswvPhoneWebview.getSettings().setBuiltInZoomControls(true);
syswvPhoneWebview.getSettings().setSupportZoom(true);
wvPhoneWebview.loadUrl("www.google.com");
SystemWebViewEngine systemWebViewEngine = (SystemWebViewEngine) wvPhoneWebview.getEngine();
syswvPhoneWebview.setWebViewClient(new DocumentViewClient(systemWebViewEngine, mActivity));
}
}
现在是webviewclient代码。
public class DocumentViewClient extends SystemWebViewClient {
private final Activity activity;
public DocumentViewClient(SystemWebViewEngine parentEngine, Activity activity) {
super(parentEngine);
this.activity = activity;
}
}