安卓原生组件webview加载h5的URL,若要h5调用安卓原生相机和相册有效需要做以下操作。
测试机:魅蓝note2 系统5.1.1
华为荣耀畅玩7x 系统8.0.0
一、h5页面相关
方便与安卓原生代码相对应且拿到相对应的file值,避免之后不必要的不匹配麻烦。
1、标签设置 [相机、相册]
2、函数代码
(1)js方法,使用FormData方法避免安卓端兼容更多的机型
// 实例化一个空对象
var data = new FormData();
//获取file文件
var file=document.getElementById(yourInputId).files[0];
//将文件加入到data中,一般FormData对象中添加数据使用append()方法
data.append(file)
// 创建一个HTTP请求
var request = new XMLHttpRequest();
// 然后使用open方法,选择传送的method和后台的URL
request.open("POST|GET", "URL");
// 最后,向后台发送我们的数据
request.send(data)
(2)如果是jquery写法如下
// 获取要传输的文件------假设只有一个文件
var file = document.getElementById(yourInputId).files[0];
// ajax传输
$.ajax({
url: URL,
type: "POST",
async: false,
cache: false,
processData: false,// 告诉jQuery不要去处理发送的数据
contentType: false,// 告诉jQuery不要去设置Content-Type请求头
data: file,
success: function(data){
alert(data);
},
error: function(err) {
alert(err);
}
});
二、Android端原生相关
(1)webview配置
WebSettings settings = webView.getSettings();
//开启JavaScript支持
settings.setJavaScriptEnabled(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
settings.setAppCacheEnabled(false);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setDomStorageEnabled(true);
settings.setDefaultTextEncodingName("UTF-8");
settings.setAllowContentAccess(true); //是否可访问Content Provider的资源,默认值 true
settings.setAllowFileAccess(true); //是否可访问本地文件,默认值 true
//是否允许通过file url加载的Javascript读取本地文件,默认值 false
settings.setAllowFileAccessFromFileURLs(false);
//是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https),默认值 false
settings.setAllowUniversalAccessFromFileURLs(false);
//支持缩放
settings.setSupportZoom(true);
//辅助WebView设置处理关于页面跳转,页面请求等操作
webView.setWebViewClient(new MyWebViewClient());
//辅助WebView处理图片上传操作
webView.setWebChromeClient(new MyChromeWebClient());
//加载地址[你自己的加载url地址]
webView.loadUrl(loadUrl);
(2)自定义MyChromeWebClient辅助webview处理除视频外调用相机的图片上传操作,如上文的文件上传标签
private class MyChromeWebClient extends WebChromeClient {
// For Android 3.0-
@SuppressWarnings("static-access")
public void openFileChooser(ValueCallback uploadMsg) {
Log.i("MainNewActivity", "openFileChoose(ValueCallback uploadMsg)");
mUploadMessage = uploadMsg;
if (videoFlag) {
recordVideo();
} else {
takePhoto();
}
}
// For Android 3.0+
@SuppressWarnings("static-access")
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
Log.d("MainNewActivity", "openFileChoose( ValueCallback uploadMsg, String acceptType )");
mUploadMessage = uploadMsg;
if (videoFlag) {
recordVideo();
} else {
takePhoto();
}
}
//For Android 4.1
@Override
public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
Log.d("MainNewActivity", "openFileChoose(ValueCallback uploadMsg, String acceptType, String capture)");
mUploadMessage = uploadMsg;
if (videoFlag) {
recordVideo();
} else {
takePhoto();
}
}
// For Android 5.0+
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
Log.d("MainNewActivity", "onShowFileChooser(ValueCallback uploadMsg, String acceptType, String capture)");
mUploadCallbackAboveL = filePathCallback;
if (videoFlag) {
recordVideo();
} else {
onenFileChooseImpleForAndroid(filePathCallback);
}
return true;
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
progressbar.setVisibility(GONE);
} else {
if (progressbar.getVisibility() == GONE)
progressbar.setVisibility(VISIBLE);
progressbar.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
}
1⃣ 其中调用录像功能相关代码
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//限制时长
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
//开启摄像机
startActivityForResult(intent, VIDEO_REQUEST);
}
2⃣ 其中调用安卓系统小于5.0的相机功能相关代码
private void takePhoto() {
File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
imageUri = Uri.fromFile(fileUri);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, PHOTO_REQUEST);
}
3⃣ 其中调用安卓系统大于5.0的相机功能相关代码
private void onenFileChooseImpleForAndroid(ValueCallback filePathCallback) {
mUploadMessageForAndroid5 = filePathCallback;
cameraIntents = new ArrayList();
File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
imageUri = Uri.fromFile(fileUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
imageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", fileUri);//通过FileProvider创建一个content类型的Uri
}
if (Build.VERSION.SDK_INT >= 23) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(MainNewActivity.this, Manifest.permission.CAMERA);
if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainNewActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
return;
} else {
openCamera();
}
} else {
openCamera();
}
}
private void openCamera() {
Intent intentCamera = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intentCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//添加这一句表示对目标应用临时授权该Uri所代表的文件
}
intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//将拍照结果保存至photo_file的Uri中,不保留在相册中
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
cameraIntents.add(intentCamera);
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent i = new Intent(Intent.ACTION_CHOOSER);
i.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
i.putExtra(Intent.EXTRA_TITLE, "File Chooser");
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
}
4⃣ 重写权限回调方法 onRequestPermissionsResult(),避免部分机型安卓系统6.0自动阻止相关权限设置,现强制开启相关权限
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
//就像onActivityResult一样这个地方就是判断你是从哪来的。
case 222:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
openCamera();
} else {
// Permission Denied
Toast.makeText(MainNewActivity.this, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
(3)给webview设置安卓原生进度条progressbar
//创建进度条
progressbar = new ProgressBar(this,null,android.R.attr.progressBarStyleHorizontal);
//设置加载进度条的高度
progressbar.setLayoutParams(new AbsoluteLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, progressHeight, 0, 0));
webView.addView(progressbar);
(4)安卓系统返回按钮设置点击按钮返回h5上个页面、h5首页点击按钮退出整个应用
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
webView.goBack();
return true;
} else {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
showExit();
}
private void showExit() {
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage("是否确定退出xx应用吗?")
.setNegativeButton("确定", (dialog1, i) -> {
//彻底关闭整个APP
int currentVersion = android.os.Build.VERSION.SDK_INT;
if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
System.exit(0);
} else {// android2.1
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.restartPackage(getPackageName());
}
dialog1.dismiss();
}).setPositiveButton("取消", (dialog12, i) -> dialog12.dismiss()).create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
(5)兼容安卓系统8.0
1⃣ 在工程目录res 文件夹下面创建xml文件夹,且在对应的xml文件夹下面创建file_paths.xml配置文件
配置文件目录结构图file_paths.xml配置文件内容如下
2⃣ AndoirdManifest.xml文件相关配置
3⃣ 调用相关
imageUri = Uri.fromFile(fileUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
imageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", fileUri);//通过FileProvider创建一个content类型的Uri
}
(6)配置部分机型调用sd卡的读取权限工具类
public class PermissionUtils {
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
/**
* Checks if the app has permission to write to device storage
* If the app does not has permission then the user will be prompted to
* grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
}
(7)最后放上完整的view层代码
public class MainNewActivity extends AppCompatActivity {
private final static int PHOTO_REQUEST = 100;
private final static int VIDEO_REQUEST = 120;
private final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 200;
private WebView webView;
private ProgressBar progressbar;
private int progressHeight = 10;
private String loadUrl = "https://www.baidu.com";
private ValueCallback mUploadMessage;
private ValueCallback mUploadCallbackAboveL;
private boolean videoFlag = false;
private Uri imageUri;
public static void launch(Context context) {
context.startActivity(new Intent(context, MainNewActivity.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PermissionUtils.verifyStoragePermissions(this);
setContentView(R.layout.activity_main_new);
initWebView();
}
private void initWebView() {
webView = (WebView) findViewById(R.id.webView);
//创建进度条
progressbar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
//设置加载进度条的高度
progressbar.setLayoutParams(new AbsoluteLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, progressHeight, 0, 0));
initWebViewSetting();
}
//初始化webViewSetting
@SuppressLint("SetJavaScriptEnabled")
private void initWebViewSetting() {
webView.addView(progressbar);
WebSettings settings = webView.getSettings();
//开启JavaScript支持
settings.setJavaScriptEnabled(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
settings.setAppCacheEnabled(false);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setDomStorageEnabled(true);
settings.setDefaultTextEncodingName("UTF-8");
settings.setAllowContentAccess(true); //是否可访问Content Provider的资源,默认值 true
settings.setAllowFileAccess(true); //是否可访问本地文件,默认值 true
//是否允许通过file url加载的Javascript读取本地文件,默认值 false
settings.setAllowFileAccessFromFileURLs(false);
//是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https),默认值 false
settings.setAllowUniversalAccessFromFileURLs(false);
//支持缩放
settings.setSupportZoom(true);
//辅助WebView设置处理关于页面跳转,页面请求等操作
webView.setWebViewClient(new MyWebViewClient());
//辅助WebView处理图片上传操作
webView.setWebChromeClient(new MyChromeWebClient());
//加载地址
webView.loadUrl(loadUrl);
}
//自定义 WebViewClient 辅助WebView设置处理关于页面跳转,页面请求等操作【处理tel协议和视频通讯请求url的拦截转发】
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.e("=url", url);
if (!TextUtils.isEmpty(url)) {
videoFlag = url.contains("vedio");
}
if (url.trim().startsWith("tel")) {//特殊情况tel,调用系统的拨号软件拨号【1111111111】
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else {
String port = url.substring(url.lastIndexOf(":") + 1, url.lastIndexOf("/"));//尝试要拦截的视频通讯url格式(808端口):【http://xxxx:808/?roomName】
if (port.equals("808")) {//特殊情况【若打开的链接是视频通讯地址格式则调用系统浏览器打开】
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else {//其它非特殊情况全部放行
view.loadUrl(url);
}
}
return true;
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//https忽略证书问题
handler.proceed();
}
@Override
public void onPageFinished(WebView view, String url) {
progressbar.setVisibility(GONE);
super.onPageFinished(view, url);
}
}
//自定义 WebChromeClient 辅助WebView处理图片上传操作【 文件上传标签】
private class MyChromeWebClient extends WebChromeClient {
// For Android 3.0-
@SuppressWarnings("static-access")
public void openFileChooser(ValueCallback uploadMsg) {
Log.i("MainNewActivity", "openFileChoose(ValueCallback uploadMsg)");
mUploadMessage = uploadMsg;
if (videoFlag) {
recordVideo();
} else {
takePhoto();
}
}
// For Android 3.0+
@SuppressWarnings("static-access")
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
Log.d("MainNewActivity", "openFileChoose( ValueCallback uploadMsg, String acceptType )");
mUploadMessage = uploadMsg;
if (videoFlag) {
recordVideo();
} else {
takePhoto();
}
}
//For Android 4.1
@Override
public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
Log.d("MainNewActivity", "openFileChoose(ValueCallback uploadMsg, String acceptType, String capture)");
mUploadMessage = uploadMsg;
if (videoFlag) {
recordVideo();
} else {
takePhoto();
}
}
// For Android 5.0+
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
Log.d("MainNewActivity", "onShowFileChooser(ValueCallback uploadMsg, String acceptType, String capture)");
mUploadCallbackAboveL = filePathCallback;
if (videoFlag) {
recordVideo();
} else {
onenFileChooseImpleForAndroid(filePathCallback);
}
return true;
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
progressbar.setVisibility(GONE);
} else {
if (progressbar.getVisibility() == GONE)
progressbar.setVisibility(VISIBLE);
progressbar.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
}
private ValueCallback mUploadMessageForAndroid5;
private List cameraIntents;
private void onenFileChooseImpleForAndroid(ValueCallback filePathCallback) {
mUploadMessageForAndroid5 = filePathCallback;
cameraIntents = new ArrayList();
File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
imageUri = Uri.fromFile(fileUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
imageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", fileUri);//通过FileProvider创建一个content类型的Uri
}
if (Build.VERSION.SDK_INT >= 23) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(MainNewActivity.this, Manifest.permission.CAMERA);
if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainNewActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
return;
} else {
openCamera();
}
} else {
openCamera();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
//就像onActivityResult一样这个地方就是判断你是从哪来的。
case 222:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
openCamera();
} else {
// Permission Denied
Toast.makeText(MainNewActivity.this, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void openCamera() {
Intent intentCamera = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intentCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//添加这一句表示对目标应用临时授权该Uri所代表的文件
}
intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//将拍照结果保存至photo_file的Uri中,不保留在相册中
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
cameraIntents.add(intentCamera);
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent i = new Intent(Intent.ACTION_CHOOSER);
i.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
i.putExtra(Intent.EXTRA_TITLE, "File Chooser");
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
}
private void takePhoto() {
File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
imageUri = Uri.fromFile(fileUri);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, PHOTO_REQUEST);
}
//录像
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//限制时长
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
//开启摄像机
startActivityForResult(intent, VIDEO_REQUEST);
}
@Override
public void onBackPressed() {
showExit();
}
private void showExit() {
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage("是否确定退出xx应用吗?")
.setNegativeButton("确定", (dialog1, i) -> {
//彻底关闭整个APP
int currentVersion = android.os.Build.VERSION.SDK_INT;
if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
System.exit(0);
} else {// android2.1
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.restartPackage(getPackageName());
}
dialog1.dismiss();
}).setPositiveButton("取消", (dialog12, i) -> dialog12.dismiss()).create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
webView.goBack();
return true;
} else {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_REQUEST) {
if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
if (mUploadCallbackAboveL != null) {
onActivityResultAboveL(requestCode, resultCode, data);
} else if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
} else if (requestCode == VIDEO_REQUEST) {
if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
if (mUploadCallbackAboveL != null) {
if (resultCode == RESULT_OK) {
mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
mUploadCallbackAboveL = null;
} else {
mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
mUploadCallbackAboveL = null;
}
} else if (mUploadMessage != null) {
if (resultCode == RESULT_OK) {
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else {
mUploadMessage.onReceiveValue(Uri.EMPTY);
mUploadMessage = null;
}
}
} else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
if (null == mUploadMessageForAndroid5)
return;
Uri result = (data == null || resultCode != RESULT_OK) ? null : data.getData();
if (result != null) {
mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
} else {
Uri[] results = new Uri[]{imageUri};
mUploadMessageForAndroid5.onReceiveValue(results);
}
mUploadMessageForAndroid5 = null;
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
if (requestCode != PHOTO_REQUEST || mUploadCallbackAboveL == null) {
return;
}
Uri[] results = null;
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
results = new Uri[]{imageUri};
} else {
String dataString = data.getDataString();
ClipData clipData = data.getClipData();
if (clipData != null) {
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
results[i] = item.getUri();
}
}
if (dataString != null)
results = new Uri[]{Uri.parse(dataString)};
}
}
mUploadCallbackAboveL.onReceiveValue(results);
mUploadCallbackAboveL = null;
}
@Override
protected void onDestroy() {
if (webView != null) {
// 如果先调用destroy()方法,则会命中if (isDestroyed()) return;这一行代码,需要先onDetachedFromWindow(),再
// destory()
ViewParent parent = webView.getParent();
if (parent != null) {
((ViewGroup) parent).removeView(webView);
}
webView.stopLoading();
// 退出时调用此方法,移除绑定的服务,否则某些特定系统会报错
webView.getSettings().setJavaScriptEnabled(false);
webView.clearHistory();
webView.clearView();
webView.removeAllViews();
webView.destroy();
}
super.onDestroy();
}
}
若有问题请留言,互助学习。