package cn.pucheng.parking.activity;
import android.Manifest;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import org.greenrobot.eventbus.EventBus;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import cn.pucheng.parking.BaseApplication;
import cn.pucheng.parking.R;
import cn.pucheng.parking.bean.MsgBean;
import cn.pucheng.parking.fragment.BaseFragment;
import cn.pucheng.parking.http.AnsynHttpRequest;
import cn.pucheng.parking.http.UrlConfig;
import cn.pucheng.parking.utils.JieKouDiaoYongUtils;
import cn.pucheng.parking.utils.SharedPreferenceUtil;
import cn.pucheng.parking.utils.ToastUtil;
import cn.pucheng.parking.zoom.DataCleanManager;
import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by zhangyonggang on 2017/8/8.
* html界面预览
*/
public abstract class BaseWebView extends BaseFragment {
private static final int LOCATION_CODE = 1;
private static final int GPS_REQUEST_CODE = 2;
private static final String TAG = BaseWebView.class.getSimpleName();
private LocationManager lm;//【位置管理】
WebView web_zhuce_bridge;
private SharedPreferenceUtil spUtil;
private ValueCallback<Uri> uploadFile;
private final static int FILECHOOSER_RESULTCODE = 1;// 表单的结果回调</span>
private ValueCallback<Uri[]> mUploadCallbackAboveL;
private ValueCallback<Uri> mUploadMessage;// 表单的数据信息
private Uri imageUri;
public Map map;
private boolean ok = false;
private LinearLayout errorView;
private double latitude;
private double longitude;
private String addrStr;
boolean isRedirect = false; //是否是重定向
boolean isPageOk = false; //目的地地址加载完成
//------
private Uri cameraUri;
private static final int REQUEST_CAMERA = 1;
private static final int REQUEST_CHOOSE = 2;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.base_webview, null);
initLocationOption();
initView(view);
loadUrl();
//硬件加速
initHardwareAccelerate();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "没有权限,请手动开启定位权限", Toast.LENGTH_SHORT).show();
// 申请一个(或多个)权限,并提供用于回调返回的获取码(用户定义)
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CALL_PHONE,
Manifest.permission.CAMERA
}, 100);
}
return view;
}
abstract void loadUrl();
/**
* 启用硬件加速
*/
private void initHardwareAccelerate() {
try {
//去除广告
getActivity().getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
ArrayList<View> outView = new ArrayList<View>();
getActivity().getWindow().getDecorView().findViewsWithText(outView, "QQ浏览器", View.FIND_VIEWS_WITH_TEXT);
int size = outView.size();
if (outView != null && outView.size() > 0) {
outView.get(0).setVisibility(View.GONE);
}
}
});
} catch (Exception e) {
}
}
public void initView(View view) {
spUtil = SharedPreferenceUtil.init(getActivity(), SharedPreferenceUtil.LOGIN_INFO, MODE_PRIVATE);
web_zhuce_bridge = view.findViewById(R.id.web_zhuce_bridge);
errorView = view.findViewById(R.id.error_view);
map = new HashMap();
map.put("Referer", "http://pucheng.ttparking.cn");
final WebSettings webSettings = web_zhuce_bridge.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setAllowFileAccess(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setUseWideViewPort(true);
webSettings.setSupportMultipleWindows(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setAppCacheMaxSize(Long.MAX_VALUE);
webSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
// this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
webSettings.setAllowContentAccess(true);
// 是否允许通过file url加载的Javascript读取本地文件,默认值 false
webSettings.setAllowFileAccessFromFileURLs(true);
// 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https),默认值 false
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setBlockNetworkImage(true);
//启用数据库
String dir = BaseApplication.getApplication().getDir("database", Context.MODE_PRIVATE).getPath();
//设置定位的数据库路径
webSettings.setGeolocationDatabasePath(dir);
webSettings.setDomStorageEnabled(true);
web_zhuce_bridge.addJavascriptInterface(new Object() {
@JavascriptInterface
public String getAuthkey() {
Log.e(TAG, "getAuthkey: " + "");
return spUtil.getString("authkey");
}
@JavascriptInterface
public int getId() {
Log.e(TAG, "getId: " + "");
return spUtil.getInt("id");
}
@JavascriptInterface
public String getPhoneNum() {
return spUtil.getString("sjh");
}
@JavascriptInterface
public void jumpToLogin() {
Intent intent = new Intent(getContext(), LoginActivity.class);
startActivity(intent);
DataCleanManager.clearAllCache(getContext());//清空缓存
spUtil = SharedPreferenceUtil.init(getContext(), SharedPreferenceUtil.LOGIN_INFO, MODE_PRIVATE);
spUtil.removeCurrentUserInfo();
SharedPreferenceUtil spUtil2 = SharedPreferenceUtil.init(getContext(), SharedPreferenceUtil.FaPiaoMore, MODE_PRIVATE);
spUtil2.removeCurrentUserInfo();
getActivity().finish();
}
@JavascriptInterface
public void mylocation() {
openGPS();
}
@JavascriptInterface
public boolean isOpenGps() {
return ok;
}
@JavascriptInterface
public void reload() {
Log.e(TAG, "reload: " + "");
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
web_zhuce_bridge.reload();
}
});
}
@JavascriptInterface
public String locationInfo() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("latitude", latitude);
map.put("longitude", longitude);
map.put("addrStr", addrStr);
String s = AnsynHttpRequest.parser.toJson(map);
return s;
}
@JavascriptInterface
public String version() {
return JieKouDiaoYongUtils.getVerName(BaseApplication.getApplication());
}
}, "UserInfo");
web_zhuce_bridge.setWebChromeClient(new MyChromeWebClient());
web_zhuce_bridge.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// 接受所有网站的证书
handler.proceed();
}
@Override
public void onReceivedError(WebView webView, int i, String s, String s1) {
errorView.setVisibility(View.VISIBLE);
web_zhuce_bridge.setVisibility(View.GONE);
errorView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
web_zhuce_bridge.onResume();
web_zhuce_bridge.reload();
errorView.setVisibility(View.GONE);
web_zhuce_bridge.setVisibility(View.VISIBLE);
}
});
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
isRedirect = true;
isPageOk = false;
}
@Override
public void onLoadResource(WebView webView, String url) {
super.onLoadResource(webView, url);
Log.e(TAG, "onLoadResource: " + url);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
return super.shouldInterceptRequest(view, request);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.e(TAG, "shouldOverrideUrlLoading: ====" + url);
//判断跳到拨打电话界面
if (url.contains("tel:")) {
String mobile = url.substring(url.lastIndexOf("/") + 1);
Uri uri = Uri.parse("tel:" + mobile);
Intent intent = new Intent(Intent.ACTION_CALL, uri);
startActivity(intent);
return true;
}
if (url.contains("baidumap")) {
try {
Intent intent = new Intent();
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException exception) {
Toast.makeText(BaseApplication.getApplication(), "未安装百度地图", Toast.LENGTH_SHORT).show();
new AlertDialog.Builder(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).setTitle("下载")
.setMessage("手机上未安装百度地图,是否下载?")
// 取消选项
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// 关闭dialog
dialogInterface.dismiss();
}
})
// 确认选项
.setPositiveButton("去下载", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String baiduStr = "https://shouji.baidu.com/software/26408462.html";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse(baiduStr);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(uri);
startActivity(intent);
}
})
.setCancelable(false)
.show();
}
} else if (url.contains("platformapi/startApp")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException exception) {
Toast.makeText(BaseApplication.getApplication(), "未安装支付宝", Toast.LENGTH_SHORT).show();
}
} else if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.M)
&& (url.contains("platformapi") && url.contains("startApp"))) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException exception) {
Toast.makeText(BaseApplication.getApplication(), "未安装支付宝", Toast.LENGTH_SHORT).show();
}
} else if (url.startsWith("weixin://wap/pay?")) {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException exception) {
Toast.makeText(BaseApplication.getApplication(), "未安装微信", Toast.LENGTH_SHORT).show();
}
} else {
web_zhuce_bridge.loadUrl(url, map);
}
/* isRedirect = false;
if (isPageOk) {
view.loadUrl(url,map);
// web_zhuce_bridge.loadUrl(url, map);
//页面跳转
//返回true表明点击网页里面的连接还是在当前的webview里跳转,不跳到浏览器
return true;
}*/
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.e(TAG, "onPageFinished: " + url);
isPageOk = isRedirect;
String index1 = UrlConfig.BASE_H5_URL + "index";
String index2 = UrlConfig.BASE_H5_URL + "myMessage";
String index3 = UrlConfig.BASE_H5_URL + "parkingRecord";
String index4 = UrlConfig.BASE_H5_URL + "personalIndex";
if (url.contains(index1) || url.contains(index2) || url.contains(index3) || url.contains(index4)) {
EventBus.getDefault().post(new MsgBean("back", true));
} else {
EventBus.getDefault().post(new MsgBean("back", false));
}
}
});
}
private boolean checkGpsIsOpen() {
boolean isOpen;
LocationManager locationManager = (LocationManager) BaseApplication.getApplication().getSystemService(Context.LOCATION_SERVICE);
isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return isOpen;
}
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
Uri[] results = null;
if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
results = new Uri[]{cameraUri};
}
if (requestCode == REQUEST_CHOOSE && resultCode == RESULT_OK) {
if (data != null) {
String dataString = data.getDataString();
if (dataString != null)
results = new Uri[]{Uri.parse(dataString)};
}
}
mUploadCallbackAboveL.onReceiveValue(results);
mUploadCallbackAboveL = null;
return;
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == GPS_REQUEST_CODE) {
if (checkGpsIsOpen()) {
ok = true;
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
} else {
ok = false;
ToastUtil.show(getActivity(), "未开启GPS定位");
}
}
if (mUploadCallbackAboveL != null) {
onActivityResultAboveL(requestCode, resultCode, data);
}
if (mUploadMessage == null) return;
Uri uri = null;
if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
uri = cameraUri;
Log.e("onActivityResult: ", uri.toString());
}
if (requestCode == REQUEST_CHOOSE && resultCode == RESULT_OK) {
uri = afterChosePic(data);
}
mUploadMessage.onReceiveValue(uri);
mUploadMessage = null;
super.onActivityResult(requestCode, resultCode, data);
}
public void openGPS() {
lm = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (ok) {//开了定位服务
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.e("BRG", "没有权限");
// 没有权限,申请权限。
// 申请授权。
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
// Toast.makeText(getActivity(), "没有权限", Toast.LENGTH_SHORT).show();
} else {
// 有权限了,去放肆吧。
// Toast.makeText(getActivity(), "有权限", Toast.LENGTH_SHORT).show();
}
} else {
new AlertDialog.Builder(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).setTitle("开启GPS")
.setMessage("确认打开GPS定位?")
// 取消选项
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// 关闭dialog
dialogInterface.dismiss();
if (BaseApplication.mLocationClient.isStarted()) {
BaseApplication.mLocationClient.disableAssistantLocation();
}
}
})
// 确认选项
.setPositiveButton("去开启", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//跳转到手机原生设置页面
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, GPS_REQUEST_CODE);
}
})
.setCancelable(false)
.show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限被用户同意。
ok = true;
web_zhuce_bridge.reload();
BaseApplication.mLocationClient.start();
BaseApplication.mLocationClient.enableAssistantLocation(web_zhuce_bridge);
} else {
ok = false;
// 权限被用户拒绝了。
// Toast.makeText(getActivity(), "定位权限被禁止,相关地图功能无法使用!", Toast.LENGTH_LONG).show();
}
}
}
}
@Override
public void onPause() {
super.onPause();
if (null != web_zhuce_bridge) {
web_zhuce_bridge.onPause();
web_zhuce_bridge.pauseTimers();
}
}
@Override
public void onResume() {
super.onResume();
if (null != web_zhuce_bridge) {
web_zhuce_bridge.resumeTimers();
web_zhuce_bridge.onResume();
}
}
/**
* 初始化定位参数配置
*/
private void initLocationOption() {
//定位服务的客户端。宿主程序在客户端声明此类,并调用,目前只支持在主线程中启动
LocationClient locationClient = new LocationClient(BaseApplication.getApplication());
//声明LocationClient类实例并配置定位参数
LocationClientOption locationOption = new LocationClientOption();
MyLocationListener myLocationListener = new MyLocationListener();
//注册监听函数
locationClient.registerLocationListener(myLocationListener);
//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选,默认gcj02,设置返回的定位结果座标系,如果配合百度地图使用,建议设置为bd09ll;
locationOption.setCoorType("gcj02");
//可选,默认0,即仅定位一次,设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
locationOption.setScanSpan(1000);
//可选,设置是否需要地址信息,默认不需要
locationOption.setIsNeedAddress(true);
//可选,设置是否需要地址描述
locationOption.setIsNeedLocationDescribe(true);
//可选,设置是否需要设备方向结果
locationOption.setNeedDeviceDirect(false);
//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
locationOption.setLocationNotify(true);
//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
locationOption.setIgnoreKillProcess(true);
//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
locationOption.setIsNeedLocationDescribe(true);
//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
locationOption.setIsNeedLocationPoiList(true);
//可选,默认false,设置是否收集CRASH信息,默认收集
locationOption.SetIgnoreCacheException(false);
//可选,默认false,设置是否开启Gps定位
locationOption.setOpenGps(true);
//可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用
locationOption.setIsNeedAltitude(false);
//设置打开自动回调位置模式,该开关打开后,期间只要定位SDK检测到位置变化就会主动回调给开发者,该模式下开发者无需再关心定位间隔是多少,定位SDK本身发现位置变化就会及时回调给开发者
locationOption.setOpenAutoNotifyMode();
//设置打开自动回调位置模式,该开关打开后,期间只要定位SDK检测到位置变化就会主动回调给开发者
locationOption.setOpenAutoNotifyMode(3000, 1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
//需将配置好的LocationClientOption对象,通过setLocOption方法传递给LocationClient对象使用
locationClient.setLocOption(locationOption);
//开始定位
locationClient.start();
}
/**
* 实现定位回调
*/
public class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
//此处的BDLocation为定位结果信息类,通过它的各种get方法可获取定位相关的全部结果
//以下只列举部分获取经纬度相关(常用)的结果信息
//更多结果信息获取说明,请参照类参考中BDLocation类中的说明
//获取纬度信息
latitude = location.getLatitude();
//获取经度信息
longitude = location.getLongitude();
//获取地址信息
addrStr = location.getAddrStr();
//获取定位精度,默认值为0.0f
float radius = location.getRadius();
//获取经纬度座标类型,以LocationClientOption中设置过的座标类型为准
String coorType = location.getCoorType();
//获取定位类型、定位错误返回码,具体信息可参照类参考中BDLocation类中的说明
int errorCode = location.getLocType();
Log.e(TAG, "onReceiveLocation: " + latitude);
Log.e(TAG, "onReceiveLocation: " + longitude);
Log.e(TAG, "onReceiveLocation: " + addrStr);
}
}
//==========
//自定义 WebChromeClient 辅助WebView处理图片上传操作【<input type=file> 文件上传标签】
public class MyChromeWebClient extends WebChromeClient {
String index1 = UrlConfig.BASE_H5_URL + "index";
String index2 = UrlConfig.BASE_H5_URL + "myMessage";
String index3 = UrlConfig.BASE_H5_URL + "parkingRecord";
String index4 = UrlConfig.BASE_H5_URL + "personalIndex";
String urlStr = UrlConfig.BASE_H5_URL + "map";
//-----------------添加了一下两个方法就可以调用定位了-----------
@Override
public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
JsResult arg3) {
Log.e(TAG, "onJsConfirm: " + arg1 + ":" + arg1 + ":" + arg2 + ":" + arg3);
if (arg0.getUrl().contains(index1)) {
return true;
}
if (arg0.getUrl().contains(urlStr)) {
arg3.confirm();
return true;
}
return super.onJsConfirm(arg0, arg1, arg2, arg3);
}
@Override
public boolean onJsAlert(WebView arg0, String arg1, String arg2,
JsResult arg3) {
Log.e(TAG, "onJsAlert: " + arg1 + ":" + arg1 + ":" + arg2 + ":" + arg3);
if (arg0.getUrl().contains(index1) || arg0.getUrl().contains(urlStr)) {
return true;
}
return super.onJsAlert(arg0, arg1, arg2, arg3);
}
@Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, true);
super.onGeolocationPermissionsShowPrompt(origin, callback);
}
// 设置应用程序的标题title
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
@Override
public boolean onShowFileChooser(WebView webView,
ValueCallback<Uri[]> filePathCallback,
FileChooserParams fileChooserParams) {
if (mUploadCallbackAboveL != null) {
mUploadCallbackAboveL.onReceiveValue(null);
} else {
mUploadCallbackAboveL = filePathCallback;
selectImage();
}
return true;
}
// Android > 4.1.1 调用这个方法
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
// 3.0 + 调用这个方法
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType) {
if (mUploadMessage != null) return;
mUploadMessage = uploadMsg;
selectImage();
}
// Android < 3.0 调用这个方法
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
@Override
public void onProgressChanged(WebView view, int progress) {
//通过图片的延迟载入,让网页能更快地显示
if (progress == 100) {
web_zhuce_bridge.getSettings().setBlockNetworkImage(false);
}
}
}
private void selectImage() {
String[] selectPicTypeStr = {"拍照", "图库"};
new AlertDialog.Builder(getActivity())
.setOnCancelListener(new ReOnCancelListener())
.setItems(selectPicTypeStr,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
// 相机拍摄
case 0:
openCarcme();
break;
// 手机相册
case 1:
chosePicture();
break;
}
}
}).show();
}
/**
* dialog监听类
*/
private class ReOnCancelListener implements DialogInterface.OnCancelListener {
@Override
public void onCancel(DialogInterface dialogInterface) {
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
}
if (mUploadCallbackAboveL != null) {
mUploadCallbackAboveL.onReceiveValue(null);
mUploadCallbackAboveL = null;
}
}
}
private void openCarcme() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String imagePaths = Environment.getExternalStorageDirectory().getPath() + "/yicaitong/Images/" + (System.currentTimeMillis() + ".jpg");
// 必须确保文件夹路径存在,否则拍照后无法完成回调
File vFile = new File(imagePaths);
if (!vFile.exists()) {
File vDirPath = vFile.getParentFile();
vDirPath.mkdirs();
} else {
if (vFile.exists()) {
vFile.delete();
}
}
if (Build.VERSION.SDK_INT >= 24) {
cameraUri = FileProvider.getUriForFile(getActivity().getApplicationContext(), "cn.pucheng.parking.fileprovider", vFile);
} else {
cameraUri = Uri.fromFile(vFile);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
/**
* 本地相册选择图片
*/
private void chosePicture() {
Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
innerIntent.setType("image/*");
Intent wrapperIntent = Intent.createChooser(innerIntent, null);
startActivityForResult(wrapperIntent, REQUEST_CHOOSE);
}
/**
* 选择照片后结束
*
* @param data
*/
private Uri afterChosePic(Intent data) {
if (data != null) {
final String path = data.getData().getPath();
if (path != null && (path.endsWith(".png") || path.endsWith(".PNG") || path.endsWith(".jpg") || path.endsWith(".JPG"))) {
return data.getData();
} else {
Toast.makeText(getActivity(), "上传的图片仅支持png或jpg格式", Toast.LENGTH_SHORT).show();
}
}
return null;
}
}