下面列出了怎么用android.webkit.ValueCallback的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void evaluateJavascript(String js, ValueCallback<String> callback) {
if(callback == null)
webView.evaluateJavascript(js,null);
final ValueCallback<String> proxyCallback = callback;
com.tencent.smtt.sdk.ValueCallback mCallback = new com.tencent.smtt.sdk.ValueCallback() {
@Override
public void onReceiveValue(Object o) {
if(o instanceof String)
proxyCallback.onReceiveValue((String) o);
}
};
webView.evaluateJavascript(js,mCallback);
}
@Override
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
// Because Activity launchMode is singleInstance,
// so we can not get result from onActivityResult when Android 4.X,
// what a pity
//
// this.uploadMsg = uploadMsg;
// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// intent.addCategory(Intent.CATEGORY_OPENABLE);
// intent.setType("*/*");
// startActivityForResult(Intent.createChooser(intent, getString(R.string.main_file_chooser)), IntentUnit.REQUEST_FILE_16);
uploadMsg.onReceiveValue(null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
FrameLayout layout = (FrameLayout) getLayoutInflater().inflate(R.layout.dialog_desc, null, false);
TextView textView = (TextView) layout.findViewById(R.id.dialog_desc);
textView.setText(R.string.dialog_content_upload);
builder.setView(layout);
builder.create().show();
}
private void detectAndHandleLoginError(WebView view, SharedPreferences prefs) {
// Only for DMM
if(view.getUrl() != null && view.getUrl().equals("http://www.dmm.com/top/-/error/area/") && prefs.getBoolean("change_cookie_start", false) && changeCookieCnt++ < 5) {
Log.i("KCVA", "Change Cookie");
new Handler().postDelayed(new Runnable(){
public void run() {
Set<Map.Entry<String, String>> dmmCookieMapSet = gameActivity.dmmCookieMap.entrySet();
for (Map.Entry<String, String> dmmCookieMapEntry : dmmCookieMapSet) {
view.evaluateJavascript("javascript:document.cookie = '" + dmmCookieMapEntry.getKey() + "';", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
Log.i("KCVA", value);
}
});
}
view.loadUrl(GameConnection.DMM_START_URL);
}
}, 5000);
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onScaleChanged(@NonNull final WebView view, final float oldScale, final float newScale) {
if (view.isShown() && mLightningView.mPreferences.getTextReflowEnabled() &&
Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
if (mIsRunning)
return;
float changeInPercent = Math.abs(100 - 100 / mZoomScale * newScale);
if (changeInPercent > 2.5f && !mIsRunning) {
mIsRunning = view.postDelayed(new Runnable() {
@Override
public void run() {
mZoomScale = newScale;
view.evaluateJavascript(Constants.JAVASCRIPT_TEXT_REFLOW, new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
mIsRunning = false;
}
});
}
}, 100);
}
}
}
/**
* Notify the host application that an SSL error occurred while loading a
* resource. The host application must call either callback.onReceiveValue(true)
* or callback.onReceiveValue(false). Note that the decision may be
* retained for use in response to future SSL errors. The default behavior
* is to pop up a dialog.
*/
@Override
public void onReceivedSslError(XWalkView view, ValueCallback<Boolean> callback, SslError error) {
final String packageName = parentEngine.cordova.getActivity().getPackageName();
final PackageManager pm = parentEngine.cordova.getActivity().getPackageManager();
ApplicationInfo appInfo;
try {
appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// debug = true
callback.onReceiveValue(true);
} else {
// debug = false
callback.onReceiveValue(false);
}
} catch (PackageManager.NameNotFoundException e) {
// When it doubt, lock it out!
callback.onReceiveValue(false);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
ValueCallback<Uri[]> uploadMessage = ((EBrowserActivity) mContext).getUploadMessage();
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
((EBrowserActivity)mContext).setUploadMessage(uploadMessage);
Intent intent = fileChooserParams.createIntent();
try
{
((EBrowserActivity)mContext).startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e)
{
uploadMessage = null;
Toast.makeText(mContext, "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
public void startPhotoPickerIntent(ValueCallback<Uri> filePathCallback, String acceptType) {
filePathCallbackLegacy = filePathCallback;
Intent fileChooserIntent = getFileChooserIntent(acceptType);
Intent chooserIntent = Intent.createChooser(fileChooserIntent, "");
ArrayList<Parcelable> extraIntents = new ArrayList<>();
if (acceptsImages(acceptType)) {
extraIntents.add(getPhotoIntent());
}
if (acceptsVideo(acceptType)) {
extraIntents.add(getVideoIntent());
}
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents.toArray(new Parcelable[]{}));
if (chooserIntent.resolveActivity(getCurrentActivity().getPackageManager()) != null) {
getCurrentActivity().startActivityForResult(chooserIntent, PICKER_LEGACY);
} else {
Log.w("Web3WevbiewModule", "there is no Activity to handle this Intent");
}
}
@Override
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
FileChooserParams fileChooserParams) {
if (this.mDelegate != null) {
return this.mDelegate.onShowFileChooser(webView, filePathCallback, fileChooserParams);
}
return super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
}
private void evaluateJs(String js, final ValueCallback<String>callback){
mWebView.evaluateJavascript(js, new com.tencent.smtt.sdk.ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
if (callback != null)
callback.onReceiveValue(value);
}
});
}
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
LOG.d(TAG, "Incoming Result");
super.onActivityResult(requestCode, resultCode, intent);
Log.d(TAG, "Request code = " + requestCode);
if (appView != null && requestCode == CordovaChromeClient.FILECHOOSER_RESULTCODE) {
ValueCallback<Uri> mUploadMessage = this.appView.getWebChromeClient().getValueCallback();
Log.d(TAG, "did we get here?");
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
Log.d(TAG, "result = " + result);
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
CordovaPlugin callback = this.activityResultCallback;
if(callback == null && initCallbackClass != null) {
// The application was restarted, but had defined an initial callback
// before being shut down.
this.activityResultCallback = appView.pluginManager.getPlugin(initCallbackClass);
callback = this.activityResultCallback;
}
if(callback != null) {
LOG.d(TAG, "We have a callback to send this result to");
callback.onActivityResult(requestCode, resultCode, intent);
}
}
public void triggerJSEvent(final String eventName, final String target, final String data) {
eval("window.Capacitor.triggerEvent(\"" + eventName + "\", \"" + target + "\", " + data + ")", new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
}
});
}
private void evaluateJavascript(String script, ValueCallback<String> resultCallback) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript(script, resultCallback);
} else {
webView.loadUrl("javascript:"+script);
}
}
@Override
public void evaluateJavascript(String js, ValueCallback<String> callback) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// For override to type casting by Jeremy
webView.evaluateJavascript(js, (com.tencent.smtt.sdk.ValueCallback) callback);
}
else
{
LOG.d(TAG, "This webview is using the old bridge");
}
}
public void setVolume(final float volume) {
String script = "javascript:setVolume(" + volume + ")";
evaluateJavascript(script, new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
}
});
}
protected void openFileChooser(ValueCallback<Uri> uploadMessage) {
MainFragment.this.openFileCallback = uploadMessage;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, getString(R.string.file_browser)), REQUEST_FILE_CHOOSER);
}
private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
mUploadMessageForAndroid5 = uploadMsg;
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "图片选择");
WebViewActivity.this.startActivityForResult(chooserIntent, 201);
}
public Builder setUriValueCallback(ValueCallback<Uri> uriValueCallback) {
mUriValueCallback = uriValueCallback;
mIsAboveLollipop = false;
mJsChannel = false;
mUriValueCallbacks = null;
return this;
}
private boolean showImageCapturePicker(final ValueCallback<Uri[]> filePathCallback) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(bridge.getActivity().getPackageManager()) == null) {
return false;
}
final Uri imageFileUri;
try {
imageFileUri = CameraUtils.createImageFileUri(bridge.getActivity(), bridge.getContext().getPackageName());
} catch (Exception ex) {
Log.e(LogUtils.getCoreTag(), "Unable to create temporary media capture file: " + ex.getMessage());
return false;
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);
bridge.cordovaInterface.startActivityForResult(new CordovaPlugin() {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
Uri[] result = null;
if (resultCode == Activity.RESULT_OK) {
result = new Uri[]{imageFileUri};
}
filePathCallback.onReceiveValue(result);
}
}, takePictureIntent, FILE_CHOOSER_IMAGE_CAPTURE);
return true;
}
@Override
public void callJs(String js, final ValueCallback<String> callback) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
this.evaluateJs(js, callback);
} else {
this.loadJs(js);
}
}
@Override
public void evaluateJavascript(String script, @Nullable ValueCallback<String> resultCallback) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
super.evaluateJavascript(script, resultCallback);
} else {
loadUrl(String.format("%s%s", JAVA_SCRIPT_PROTOCOL, script));
}
}
@Override
public void evaluateJavascript(String js, ValueCallback<String> callback) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript(js, callback);
}
else
{
LOG.d(TAG, "This webview is using the old bridge");
}
}
public WebViewSdkCompat.ValueCallback<Uri> getCompatCallback(final ValueCallback<Uri> uploadMsg){
return new WebViewSdkCompat.ValueCallback<Uri>() {
@Override
public void onReceiveValue(Uri uri) {
uploadMsg.onReceiveValue(uri);
}
};
}
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
if (fileChooseListener.getValueCallbackSingleUri() != null) {
fileChooseListener.getValueCallbackSingleUri().onReceiveValue(null);
}
fileChooseListener.setValueCallbackSingleUri(uploadMsg);
startChooserActivity();
}
private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
mActivity.startActivityForResult(Intent.createChooser(i, "文件选择"), FILECHOOSER_RESULTCODE);
}
@Override
public void showFileChooser(ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.filePathCallback = filePathCallback;
try {
Intent intent = fileChooserParams.createIntent();
startActivityForResult(intent, IntentUnit.REQUEST_FILE_21);
} catch (Exception e) {
NinjaToast.show(this, R.string.toast_open_file_manager_failed);
}
}
}
private void clearCookiesAsync(final Callback callback) {
getCookieManager().removeAllCookies(
new ValueCallback<Boolean>() {
@Override
public void onReceiveValue(Boolean value) {
mCookieSaver.onCookiesModified();
callback.invoke(value);
}
});
}
public static void removeAllCookies(@Nullable ValueCallback<Boolean> callback) {
if (callback == null) {
callback = getDefaultIgnoreCallback();
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().removeAllCookie();
toSyncCookies();
callback.onReceiveValue(!CookieManager.getInstance().hasCookies());
return;
}
CookieManager.getInstance().removeAllCookies(callback);
toSyncCookies();
}
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
this.openFileChooser(uploadMsg, "*/*");
}
/** Add the evaulate Javascript method **/
void evaluateJavascript(String js, ValueCallback<String> callback);
public WebPlayerView(Context context, String viewId, JSONObject webSettings, JSONObject webPlayerSettings) {
super(context);
this.viewId = viewId;
WebSettings settings = getSettings();
if(Build.VERSION.SDK_INT >= 16) {
settings.setAllowFileAccessFromFileURLs(false);
settings.setAllowUniversalAccessFromFileURLs(false);
}
if (Build.VERSION.SDK_INT >= 19) {
try {
_evaluateJavascript = WebView.class.getMethod("evaluateJavascript", String.class, ValueCallback.class);
} catch(NoSuchMethodException e) {
DeviceLog.exception("Method evaluateJavascript not found", e);
_evaluateJavascript = null;
}
}
settings.setAppCacheEnabled(false);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setDatabaseEnabled(false);
settings.setDomStorageEnabled(false);
settings.setGeolocationEnabled(false);
settings.setJavaScriptEnabled(true);
settings.setLoadsImagesAutomatically(true);
settings.setPluginState(WebSettings.PluginState.OFF);
settings.setRenderPriority(WebSettings.RenderPriority.NORMAL);
settings.setSaveFormData(false);
settings.setSavePassword(false);
setHorizontalScrollBarEnabled(false);
setVerticalScrollBarEnabled(false);
setInitialScale(0);
setBackgroundColor(Color.TRANSPARENT);
ViewUtilities.setBackground(this, new ColorDrawable(Color.TRANSPARENT));
setBackgroundResource(0);
setSettings(webSettings, webPlayerSettings);
setWebViewClient(new WebPlayerClient());
setWebChromeClient(new WebPlayerChromeClient());
setDownloadListener(new WebPlayerDownloadListener());
addJavascriptInterface(new WebPlayerBridgeInterface(viewId), "webplayerbridge");
WebPlayerViewCache.getInstance().addWebPlayer(viewId, this);
this.subscribeOnLayoutChange();
}