package com.tecsun.tsb.jinzhou.activity;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tecsun.tsb.jinzhou.R;
import com.tecsun.tsb.res.utils.StorageUtils;
import java.io.File;
import io.reactivex.functions.Consumer;
public class WebActivity extends Activity {
private final static String TAG = "test";
private WebView webView;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mUploadCallbackAboveL;
private final static int PHOTO_REQUEST = 100;
private final static int VIDEO_REQUEST = 110;
private final static int FILE_REQUEST = 120;
// private final static String url = "https://www.iesdouyin.com/share/video/0000000000000000000/?region=CN&mid=0000000000000000000&u_code=0&did=MS4wLjABAAAA1c3F6xo_GKJOSjO556tUosrgAHTenuZD-1VYYy_Ctnt7j_MvNG5ewQSOVySJ3nzZ&iid=MS4wLjABAAAAd8E_2AZ60H2bGuxII71tThJMyV8C9tR3ODGMC8UgUVI-RcDNZlNNotT-htfofxtv&with_sec_did=1&titleType=title&share_sign=4XqoTQU9Uohaaa1IfbLARkllTKhDjarAi1yLUzZttPY-&share_version=310000&ts=1723319925&from_aid=1128&from_ssr=1&utm_source=copy&utm_campaign=client_share&utm_medium=android&app=aweme&activity_info=%7B%22social_author_id%22%3A%22820683398974075%22%2C%22social_share_id%22%3A%22ccfecb8f-e3d2-423c-8cd3-35bd074f949f%22%2C%22social_share_time%22%3A%221723319933%22%2C%22social_share_user_id%22%3A%220%22%7D"; // 抖音视频链接,抖音分享之后浏览器打开的那个链接
private final static String url = "https://live.douyin.com/739453887773"; // 抖音直播链接
private LinearLayout parentLayout;
private Uri imageUri;
private boolean isVideo = false;
private String acceptType;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
initView();
initData();
}
protected void initView() {
parentLayout = (LinearLayout) this
.findViewById(R.id.parentLayout);
webView = new WebView(this);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
webView.setLayoutParams(lp);
parentLayout.addView(webView);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
WebSettings settings = webView.getSettings();
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
//注意这里
settings.setDomStorageEnabled(true);
settings.setDefaultTextEncodingName("UTF-8");
settings.setAllowContentAccess(true); // 是否可访问Content Provider的资源,默认值 true
settings.setAllowFileAccess(true); // 是否可访问本地文件,默认值 true
settings.setAllowFileAccessFromFileURLs(false); // 是否允许通过file url加载的Javascript读取本地文件,默认值 false
settings.setAllowUniversalAccessFromFileURLs(false); // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https),默认值 false
//开启JavaScript支持
settings.setJavaScriptEnabled(true);
// 支持缩放
settings.setSupportZoom(true);
// settings.setMediaPlaybackRequiresUserGesture(false);
//注意这里 辅助WebView设置处理关于页面跳转,页面请求等操作
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url == null) return false;
Log.e("shouldOverrideUrl", "shouldOverrideUrlLoading: "+url);
try {
// 拦截非http和https的url的加载,否则会报错:ERR_UNKNOWN_URL_SCHEME
if (!url.startsWith("http://") && !url.startsWith("https://")) {
//以下跳转到抖音
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// startActivity(intent);
return true;
}
} catch (Exception e) {//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
return true;//没有安装该app时,返回true,表示拦截自定义链接,但不跳转,避免弹出上面的错误页面
}
//如果有视频或者别的url 可以在此处进行判断处理
if (!TextUtils.isEmpty(url)) {
isVideo = url.contains("vedio");
}
// TODO Auto-generated method stub
//返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
//注意这里 辅助WebView处理图片上传操作
webView.setWebChromeClient(new MyChromeWebClient());
}
protected void initData() {
webView.loadUrl(url);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
if (parentLayout!= null && webView != null){
parentLayout.removeView(webView);
webView.stopLoading();
webView.getSettings().setJavaScriptEnabled(false);
webView.clearHistory();
webView.clearView();
webView.removeAllViews();
try {
webView.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
super.onDestroy();
}
/**
* 注意申请读取相机和读取内存的权限
*/
private void startGetPhoto() {
new RxPermissions(this).request(Manifest.permission.READ_EXTERNAL_STORAGE)
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) {
if (aBoolean) {
new RxPermissions(WebActivity.this).request(Manifest.permission.CAMERA)
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) {
if (aBoolean) {
//启动拍照或者选择相册图片文件
showPhotoChooser();
} else {
Toast.makeText(WebActivity.this, "摄像机权限被拒绝,请在设置里面开启相应权限,若无相应权限部分功能将无法使用", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 100);
}
}
});
} else {
Toast.makeText(WebActivity.this, "读取权限被拒绝,请在设置里面开启相应权限,若无相应权限部分功能将无法使用", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 100);
}
}
});
}
//自定义 WebChromeClient 辅助WebView处理图片上传操作【<input type=file> 文件上传标签】
public class MyChromeWebClient extends WebChromeClient {
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
}
// For Android 3.0-
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
if (isVideo){
recordVideo();
}else {
startGetPhoto();
}
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
acceptType = acceptType;
if (isVideo){
recordVideo();
}else {
startGetPhoto();
}
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
acceptType = acceptType;
if (isVideo){
recordVideo();
}else {
startGetPhoto();
}
}
// For Android 5.0+
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
mUploadCallbackAboveL = filePathCallback;
acceptType = fileChooserParams.getAcceptTypes()[0];
if (fileChooserParams.isCaptureEnabled()){
showCapture();
}else {
startGetPhoto();
}
return true;
}
}
/**
* 打开选择文件/相机
*/
private void showCapture() {
// Intent intentPhoto = new Intent(Intent.ACTION_PICK);
Intent intentPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPhoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
File fileUri = new File(StorageUtils.getCacheDirectory(this) + "/"+SystemClock.currentThreadTimeMillis() + ".jpg");
// if(fileUri.exists()){
// fileUri.delete();
// }
// fileUri = new File(StorageUtils.getCacheDirectory(this) + "/" + "pic.jpg");
imageUri = Uri.fromFile(fileUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
imageUri = FileProvider.getUriForFile(this, "com.tecsun.tsb.jinzhou.pos.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
}
//调用系统相机
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);
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_TITLE, "Photo Chooser");
chooser.putExtra(Intent.EXTRA_INTENT, intentPhoto);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{intentCamera});
startActivityForResult(chooser, PHOTO_REQUEST);
}
/**
* 打开选择文件/相机
*/
private void showPhotoChooser() {
// Intent intentPhoto = new Intent(Intent.ACTION_PICK);
Intent intentPhoto = new Intent(Intent.ACTION_GET_CONTENT);
// Intent intentPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPhoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
File fileUri = new File(StorageUtils.getCacheDirectory(this) + "/"+SystemClock.currentThreadTimeMillis() + ".jpg");
imageUri = Uri.fromFile(fileUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
imageUri = FileProvider.getUriForFile(this, "com.tecsun.tsb.jinzhou.pos.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
}
intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//调用系统相机
Intent intentCamera = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intentCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
}
intentCamera.setAction(Intent.ACTION_GET_CONTENT);
//将拍照结果保存至photo_file的Uri中,不保留在相册中
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_TITLE, "Photo Chooser");
chooser.putExtra(Intent.EXTRA_INTENT, intentPhoto);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{intentCamera});
startActivityForResult(chooser, FILE_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 boolean onKeyDown(int keyCode, KeyEvent event) {
//如果按下的是回退键且历史记录里确实还有页面
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
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, null);
} else if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
if (requestCode == FILE_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;
}
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
if ( 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;
}
}
android webview打开抖音指定页面(不跳转抖音) 2024-08-11
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 导致极光推送接受推送消息点击不跳转情况是因为: i.setFlags(Intent.FLAG_ACTIVITY_...
- 通常有这么一个场景,就是分享内容到微信朋友圈等,然后点击内容中的某个按钮就可以唤起自家应用。 这里要讲的也是使用 ...
- 需求:某层次很深的一个acticity有个退出登录按钮难点:for循环finish太不优雅了实现: 第一步: 工具...
- iOS页面跳转方式 [self presentViewController:viewController anim...
- 在项目中遇到要求在NSObject类中跳转到登录页面的需求,我们利用根控制器可以完美跳转。 LoginViewCo...