1、XMl布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<include
android:id="@+id/layout_title"
layout="@layout/layout_top_bar" />
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="3dip"
/>
<WebView
android:id="@+id/web_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/layout_title" />
</LinearLayout>
2、自定义弹出选择布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_dialog"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#09000000">
<!--三个按钮 -->
<LinearLayout
android:id="@+id/addpic_bot_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#fff"
android:orientation="vertical">
<LinearLayout
android:id="@+id/layout_btn_two"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<Button
android:id="@+id/addpic_bot_btn1"
android:layout_width="match_parent"
android:layout_height="99px"
android:background="@null"
android:gravity="center"
android:text="相册"
android:textColor="#000"
android:textSize="30px"/>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#bebebe"
/>
<Button
android:id="@+id/addpic_bot_btn2"
android:layout_width="match_parent"
android:layout_height="99px"
android:layout_marginTop="1dp"
android:background="@null"
android:gravity="center"
android:text="相机"
android:textColor="#000"
android:textSize="30px"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#bebebe"
/>
<Button
android:id="@+id/addpic_bot_btn3"
android:layout_width="match_parent"
android:layout_height="99px"
android:layout_marginBottom="20px"
android:layout_marginLeft="20px"
android:layout_marginRight="20px"
android:layout_marginTop="17px"
android:background="#fff"
android:gravity="center"
android:text="取消"
android:textColor="#000"
android:textSize="30px"/>
</LinearLayout>
</RelativeLayout>
3、activiity页面
public class WebActivity extends BaseAutoActivity {
Context mContext;
private static final int REQUEST_CODE_ALBUM = 0x01;
private static final int REQUEST_CODE_CAMERA = 0x02;
private static final int REQUEST_CODE_PERMISSION_CAMERA = 0x03;
private static final int REQUEST_CODE_Viedio= 0x05;
// WebView mWebView;
private PopupWindow mPowChangeImg;// 选择图片的PopupWindow
@BindView(R.id.progressBar1)
ProgressBar progressbar;
TextView tvClose;
private ValueCallback<Uri> uploadMessage;
private ValueCallback<Uri[]> uploadMessageAboveL;
private String mCurrentPhotoPath;
private String mLastPhothPath;
private Thread mThread;
@BindView(R.id.web_main)
WebView mWebview;
private int post;
private int clickSelect,isClickPicOrVie;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
mContext = this;
ExitSystemTask.getInstance().putActivity("WebActivity", this);
ButterKnife.bind(this);
urlIntern=getIntent().getStringExtra("urlIntern");
mTvTitle.setText(title);
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebview.getSettings().setBuiltInZoomControls(true);
mWebview.getSettings().setSupportZoom(true);
mWebview.getSettings().setUseWideViewPort(true);
mWebview.getSettings().setLoadWithOverviewMode(true);
mWebview.getSettings().setGeolocationEnabled(true);
mWebview.getSettings().setDomStorageEnabled(true);
AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT, 6, 0, 0));
ClipDrawable d = new ClipDrawable(new ColorDrawable(getResources().getColor(R.color.home_line)), Gravity.LEFT, ClipDrawable.HORIZONTAL);
progressbar.setProgressDrawable(d);
mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWebview.loadUrl(urlIntern);
mWebview.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
});
mWebview.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressbar.setProgress(newProgress);
if (newProgress == 100) {
progressbar.setVisibility(View.GONE);
}
}
//For Android >= 5.0
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
uploadMessageAboveL = filePathCallback;
if(!TextUtils.isEmpty(fileChooserParams.getAcceptTypes()[0])){
showPopThImg(1);
}else{
showPopThImg(2);
}
return true;
}
//For Android >= 4.1
public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
uploadMessage = valueCallback;
if(!"".equals(acceptType)){//区分点击的图片选择还是录制
showPopThImg(1);
}else{
showPopThImg(2);
}
}
});
}
private void initView() {
//webview
mWebview.loadUrl(url);
mWebview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
// 返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
view.loadUrl(url);
return true;
}
});
}
@Override
public void onBackPressed() {
if (mWebview != null && mWebview.canGoBack()) {
mWebview.goBack();
} else {
finish();
}
}
@OnClick({R.id.ll_left})
public void onClick(View v) {
switch (v.getId()) {
case R.id.ll_left:
onBackPressed();
break;
}
}
@Override
public void configActionBar() {
mBtnLeft.setVisibility(View.VISIBLE);
}
@Override
public void requestCallBack(String jsonData, RequestType type) {
mWebview.loadDataWithBaseURL(null, getNewContent(jsonData), "text/html", "utf-8", null);
concreteSubject = ConcreteSubject.getInstance();
concreteSubject.read(post);
}
@Override
public void requestFailed(String error, RequestType type) {
}
public static String getNewContent(String htmltext){
Document doc= Jsoup.parse(htmltext);
Elements elements=doc.getElementsByTag("img");
for (Element element : elements) {
element.attr("width","100%").attr("height","auto");
}
return doc.toString();
}
private void sendTwoRequest(String departId){
Map<String,String> params=new HashMap<>();
params.put("articleId",departId);
Call<BaseBean> call=client.getArticle(params);
sendRequest(call,RequestType.outpatient);
}
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(clickSelect==1){
takePhoto();
}else if(clickSelect==2){
takeViedio();
}
}
};
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults == null && grantResults.length == 0) {
return;
}
if (requestCode == REQUEST_CODE_PERMISSION_CAMERA) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(clickSelect==2){
takeViedio();
}else{
takePhoto();
}
} else {
// Permission Denied
new AlertDialog.Builder(mContext)
.setTitle("无法拍照")
.setMessage("您未授予拍照权限")
.setNegativeButton("取消", null)
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent localIntent = new Intent();
localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
localIntent.setData(Uri.fromParts("package", getPackageName(), null));
startActivity(localIntent);
}
}).create().show();
}
}
}
/**
* 拍照
*/
private void takePhoto() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageName = timeStamp + ".jpg";
File rootPath = new File(Environment.getExternalStorageDirectory()
.getPath() + "/temp");
// File rootPath = new File(getFilesDir() + "/qdcc");
if (!rootPath.exists()) {
rootPath.mkdirs();
}
StringBuilder fileName = new StringBuilder();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File tempFile = new File(rootPath, imageName);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", new File
(rootPath, imageName));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
} else {
Uri uri = Uri.fromFile(new File(rootPath, imageName));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
mCurrentPhotoPath = tempFile.getAbsolutePath();
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
/**
* 拍照
*/
private void takeViedio() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageName = timeStamp + ".mp4";
// imageUri = Uri.fromFile(new File(Environment
// .getExternalStorageDirectory(), imageName));
File rootPath = new File(Environment.getExternalStorageDirectory()
.getPath() + "/temp");
// File rootPath = new File(getFilesDir() + "/qdcc");
if (!rootPath.exists()) {
rootPath.mkdirs();
}
StringBuilder fileName = new StringBuilder();
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File tempFile = new File(rootPath, imageName);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", new File
(rootPath, imageName));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
} else {
Uri uri = Uri.fromFile(new File(rootPath, imageName));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
mCurrentPhotoPath = tempFile.getAbsolutePath();
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
/**
* 选择相册照片
*/
private void chooseAlbumPic(int isSelect) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
if(isSelect==1){
i.setType("image/*");
}else{
i.setType("video/*");
}
startActivityForResult(Intent.createChooser(i, "Image Chooser"), REQUEST_CODE_ALBUM);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_ALBUM || requestCode == REQUEST_CODE_CAMERA) {
if (uploadMessage == null && uploadMessageAboveL == null) {
return;
}
//取消拍照或者图片选择时
if (resultCode != RESULT_OK) {
//一定要返回null,否则<input file> 就是没有反应
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(null);
uploadMessageAboveL = null;
}
}
//拍照成功和选取照片时
if (resultCode == RESULT_OK) {
Uri imageUri = null;
switch (requestCode) {
case REQUEST_CODE_ALBUM:
if (data != null) {
imageUri = data.getData();
}
break;
case REQUEST_CODE_CAMERA:
if (!TextUtils.isEmpty(mCurrentPhotoPath)) {
File file = new File(mCurrentPhotoPath);
Uri localUri = Uri.fromFile(file);
Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
sendBroadcast(localIntent);
imageUri = Uri.fromFile(file);
mLastPhothPath = mCurrentPhotoPath;
}
break;
}
//上传文件
if (uploadMessage != null) {
uploadMessage.onReceiveValue(imageUri);
uploadMessage = null;
}
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(new Uri[]{imageUri});
uploadMessageAboveL = null;
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mThread = null;
mHandler = null;
}
/**
* 选择 从相机 还是相册 修改头像
*
* @Title: showPopupWindow void
* @author limm
* @since 2015-10-19 V 1.0
*/
@SuppressWarnings("deprecation")
private void showPopThImg(final int isSelect) {
isClickPicOrVie=isSelect;
/**
* 从底部弹出的布局 layout_pop_camera为 布局文件
*/
View view = (RelativeLayout) LayoutInflater.from(this).inflate(
R.layout.layout_pop_camera, null);
RelativeLayout relativeLayout = (RelativeLayout) view
.findViewById(R.id.relative_dialog);
Button firstButton = (Button) view.findViewById(R.id.addpic_bot_btn1);
Button secButton = (Button) view.findViewById(R.id.addpic_bot_btn2);
Button thirdButton = (Button) view.findViewById(R.id.addpic_bot_btn3);
Button fourButton=(Button)view.findViewById(R.id.addpic_bot_btn4);
TextView mTv=view.findViewById(R.id.line_bot_btn4);
mTv.setVisibility(View.VISIBLE);
firstButton.setText("相册");
// fourButton.setText("");
fourButton.setVisibility(View.GONE);
switch (isSelect){
case 1:
secButton.setText("相机");
fourButton.setVisibility(View.GONE);
break;
case 2:
secButton.setText("录制");
fourButton.setVisibility(View.GONE);
break;
}
if (mPowChangeImg == null) {
mPowChangeImg = new PopupWindow(this);
mPowChangeImg.setBackgroundDrawable(new BitmapDrawable());
// popupWindow.setFocusable(true); // 设置PopupWindow可获得焦点
mPowChangeImg.setTouchable(true); // 设置PopupWindow可触摸
mPowChangeImg.setOutsideTouchable(true); // 设置非PopupWindow区域可触摸
/**
* PopupWindow 的动画样式
*/
// mPowChangeImg.setAnimationStyle(R.style.MyDialog);
}
mPowChangeImg.setContentView(view);
mPowChangeImg.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
mPowChangeImg.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
mPowChangeImg.showAtLocation(mWebview, Gravity.BOTTOM, 0, 0);
mPowChangeImg.update();
// 从相册拍照
firstButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 打开图库
chooseAlbumPic(isSelect);
mPowChangeImg.dismiss();
}
});
// 拍照
secButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isSelect==2){
clickSelect=2;
}else{
clickSelect=1;
}
if(!TextUtils.isEmpty(mLastPhothPath)){
//上一张拍照的图片删除
mThread = new Thread(new Runnable() {
@Override
public void run() {
File file = new File(mLastPhothPath);
if(file!= null){
file.delete();
}
mHandler.sendEmptyMessage(1);
}
});
mThread.start();
}else{
//请求拍照权限
if (ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
if(clickSelect==2){
takeViedio();
}else{
takePhoto();
}
} else {
ActivityCompat.requestPermissions(WebActivity.this, new String[]{android.Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSION_CAMERA);
}
}
mPowChangeImg.dismiss();
}
});
fourButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clickSelect=2;
if(!TextUtils.isEmpty(mLastPhothPath)){
//上一张拍照的图片删除
mThread = new Thread(new Runnable() {
@Override
public void run() {
File file = new File(mLastPhothPath);
if(file!= null){
file.delete();
}
mHandler.sendEmptyMessage(1);
}
});
mThread.start();
}else{
//请求拍照权限
if (ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
takeViedio();
} else {
ActivityCompat.requestPermissions(WebActivity.this, new String[]{android.Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSION_CAMERA);
}
}
}
});
// 取消
thirdButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(null);
uploadMessageAboveL = null;
}
mPowChangeImg.dismiss();
// mAllLayout.setVisibility(View.GONE);
}
});
relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//一定要返回null,否则<input type='file'>
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(null);
uploadMessageAboveL = null;
}
mPowChangeImg.dismiss();
}
});
}
}