This commit is contained in:
2024-12-17 18:12:08 +09:00
parent 10ac465aba
commit 4d8b9b728b
17 changed files with 300 additions and 199 deletions
@@ -58,9 +58,13 @@ import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import androidx.lifecycle.ReportFragment.Companion.reportFragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kr.lunaticbum.awesomewebview.databinding.AwesomeWebViewBinding
import kr.lunaticbum.awesomewebview.enums.Position
import kr.lunaticbum.awesomewebview.helpers.BitmapHelper
@@ -95,6 +99,7 @@ import kotlin.math.abs
open class AwesomeWebViewActivity : AppCompatActivity(), View.OnClickListener,
Handler.Callback {
var mediaUrls = arrayListOf<String>()
protected var key: Int = 0
protected var rtl: Boolean = false
@@ -791,8 +796,19 @@ open class AwesomeWebViewActivity : AppCompatActivity(), View.OnClickListener,
webView!!.setOnLongClickListener(OnLongClickListener {
val hitTestResult = webView!!.hitTestResult
// 如果是图片类型或者是带有图片链接的类型
if (hitTestResult.type == HitTestResult.IMAGE_TYPE ||
LogUtil.e("hitTestResult.type >>> ${hitTestResult.type}")
LogUtil.e("hitTestResult.extra >>> ${hitTestResult.extra}")
if(hitTestResult.type==0) {
webView?.evaluateJavascript("document.getElementsByTagName('iframe')",
object : ValueCallback<String> {
override fun onReceiveValue(value: String?) {
val html = value?.replace("\\u003C", "<")
onHtml(html)
}
})
}
else if (hitTestResult.type == HitTestResult.IMAGE_TYPE ||
hitTestResult.type == HitTestResult.SRC_IMAGE_ANCHOR_TYPE
) {
if (!showMenuSavePhoto) {
@@ -807,65 +823,53 @@ open class AwesomeWebViewActivity : AppCompatActivity(), View.OnClickListener,
builder?.setItems(
items
) { dialog, which ->
PermissionHelper.CheckPermissions(
this@AwesomeWebViewActivity,
object : CheckPermissionListener {
override fun onAllGranted(sync: Boolean) {
val url = hitTestResult.extra
// 下载图片到本地
CookieSyncManager.createInstance(this@AwesomeWebViewActivity)
CookieSyncManager.getInstance().sync()
val cookieManager =
CookieManager.getInstance()
val cookie =
cookieManager.getCookie(webView!!.url)
DownPicUtil.downPic(
url,
webView!!.settings.userAgentString,
webView!!.url,
cookie,
object : DownFinishListener {
override fun onDownFinish(path: String) {
if (showToastPhotoSavedOrFailed) {
Toast.makeText(
this@AwesomeWebViewActivity,
resources.getString(
stringResPhotoSavedTo
) + path,
Toast.LENGTH_LONG
).show()
}
// 最后通知图库更新
applicationContext.sendBroadcast(
Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://$path")
)
)
}
override fun onError() {
if (showToastPhotoSavedOrFailed) {
Toast.makeText(
this@AwesomeWebViewActivity,
resources.getString(
stringResPhotoSaveFailed
),
Toast.LENGTH_LONG
).show()
}
}
})
LogUtil.e("hitTestResult.extra >>> ${dialog} ,${which}")
val url = hitTestResult.extra
LogUtil.e("hitTestResult.extra >>> ${hitTestResult.extra}")
CookieSyncManager.createInstance(applicationContext)
CookieSyncManager.getInstance().sync()
val cookieManager =
CookieManager.getInstance()
val cookie =
cookieManager.getCookie(webView!!.url)
DownPicUtil.downPic(
File(Environment.getExternalStorageDirectory(),"bums").path,
url,
webView!!.settings.userAgentString,
webView!!.url,
cookie,
object : DownFinishListener {
override fun onDownFinish(path: String) {
if (showToastPhotoSavedOrFailed) {
Toast.makeText(
applicationContext,
resources.getString(
stringResPhotoSavedTo
) + path,
Toast.LENGTH_LONG
).show()
}
// 最后通知图库更新
applicationContext.sendBroadcast(
Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://$path")
)
)
}
override fun onPartlyGranted(
permissionsDenied: List<String>,
sync: Boolean
) {
override fun onError() {
if (showToastPhotoSavedOrFailed) {
Toast.makeText(
applicationContext,
resources.getString(
stringResPhotoSaveFailed
),
Toast.LENGTH_LONG
).show()
}
}
},
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
})
}
val dialog = builder?.create()
dialog?.show()
@@ -874,27 +878,27 @@ open class AwesomeWebViewActivity : AppCompatActivity(), View.OnClickListener,
false
})
webView!!.setOnTouchListener(object : OnTouchListener {
private var xDown = 0f
private var yDown = 0f
private var timeDown: Long = 0
override fun onTouch(v: View, event: MotionEvent): Boolean {
if (v === webView && event.action == MotionEvent.ACTION_DOWN) {
xDown = event.x
yDown = event.y
timeDown = System.currentTimeMillis()
} else if (v === webView && event.action == MotionEvent.ACTION_UP) {
if (abs((xDown - event.x).toDouble()) < 50 && abs(
(yDown - event.y).toDouble()
) < 50 && System.currentTimeMillis() - timeDown < 200
) {
// https://stackoverflow.com/a/5125620
handler.sendEmptyMessageDelayed(MSG_CLICK_ON_WEBVIEW, 500)
}
}
return false
}
})
// webView!!.setOnTouchListener(object : OnTouchListener {
// private var xDown = 0f
// private var yDown = 0f
// private var timeDown: Long = 0
// override fun onTouch(v: View, event: MotionEvent): Boolean {
// if (v === webView && event.action == MotionEvent.ACTION_DOWN) {
// xDown = event.x
// yDown = event.y
// timeDown = System.currentTimeMillis()
// } else if (v === webView && event.action == MotionEvent.ACTION_UP) {
// if (abs((xDown - event.x).toDouble()) < 50 && abs(
// (yDown - event.y).toDouble()
// ) < 50 && System.currentTimeMillis() - timeDown < 200
// ) {
// // https://stackoverflow.com/a/5125620
// handler.sendEmptyMessageDelayed(MSG_CLICK_ON_WEBVIEW, 500)
// }
// }
// return false
// }
// })
val settings = webView!!.settings
@@ -1239,6 +1243,10 @@ open class AwesomeWebViewActivity : AppCompatActivity(), View.OnClickListener,
}
}
open protected fun onHtml(value: String?) {
}
protected fun buildWebView(): WebView {
return VideoEnabledWebView(this)
}
@@ -1405,6 +1413,8 @@ open class AwesomeWebViewActivity : AppCompatActivity(), View.OnClickListener,
}
}
open protected var pdfListner : PDFPrint.OnPDFPrintListener? = null
override fun onClick(v: View) {
val viewId = v.id
if (viewId == R.id.close) {
@@ -1443,16 +1453,23 @@ open class AwesomeWebViewActivity : AppCompatActivity(), View.OnClickListener,
if (path.exists() == false) {
path.mkdirs()
}
val file = File(path, fileName)
PDFPrint.generatePDFFromWebView(file,webView,object :PDFPrint.OnPDFPrintListener {
override fun onSuccess(file: File?) {
LogUtil.e("file.absolutePath >>> ${file?.absolutePath ?: "fail"}")
}
override fun onError(exception: java.lang.Exception?) {
exception?.printStackTrace()
val file = File(path, fileName)
PDFPrint.generatePDFFromWebView(
file,
webView,
pdfListner ?: object : PDFPrint.OnPDFPrintListener {
override fun onSuccess(file: File?) {
LogUtil.e("file.absolutePath >>> ${file?.absolutePath ?: "fail"}")
}
override fun onError(exception: java.lang.Exception?) {
LogUtil.e("generatePDFFromWebView >>> fail")
exception?.printStackTrace()
}
}
})
)
hideMenu()
} else if (viewId == R.id.menuFind) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) webView!!.showFindDialog(
@@ -1849,6 +1866,7 @@ open class AwesomeWebViewActivity : AppCompatActivity(), View.OnClickListener,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
return File.createTempFile(new_name, if (isVideo) ".mp4" else ".jpg", sd_directory)
}
var hasYoutubePlayer = false
open fun webviewOnPageFinished(){}
inner class MyWebViewClient : WebViewClient() {
@@ -1865,11 +1883,15 @@ open class AwesomeWebViewActivity : AppCompatActivity(), View.OnClickListener,
ByteArrayInputStream("".toByteArray())
)
}
val url = request.url.toString()
if(!hasYoutubePlayer) {
hasYoutubePlayer = url.toLowerCase(Locale.ROOT)
.contains("https://www.youtube.com/s/player".toLowerCase(Locale.ROOT))
}
if (url.contains("streamable.com")) {
mediaUrls.add(url)
}
if (url.toLowerCase(Locale.ROOT)
.contains("ads".toLowerCase(Locale.ROOT))) {
LogUtil.e("shouldInterceptRequest request url contains ads >>> ${request.url.toString()}")
@@ -8,6 +8,8 @@ import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
@@ -28,26 +30,42 @@ public class DownPicUtil {
* @param url
*/
public static void downPic(String url, DownFinishListener downFinishListener){
downPic(url, null, null, null, downFinishListener);
downPic(null, url, null, null, null, downFinishListener);
}
/**
* Download the pic
* @param url
*/
public static void downPic(String url, String userAgent, String referer, String cookie, DownFinishListener downFinishListener){
// 获取存储卡的目录
String filePath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filePath + File.separator + Environment.DIRECTORY_DOWNLOADS);
if(!file.exists()){
file.mkdirs();
public static void downPic(String path , String url, String userAgent, String referer, String cookie, DownFinishListener downFinishListener){
if(path == null) {
String filePath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filePath + File.separator + Environment.DIRECTORY_DOWNLOADS);
if (!file.exists()) {
file.mkdirs();
}
loadPic(file.getPath(), url, userAgent, referer, cookie, downFinishListener, false);
} else {
loadPic(path, url, userAgent, referer, cookie, downFinishListener, false);
}
loadPic(file.getPath(), url, userAgent, referer, cookie, downFinishListener);
}
private static void loadPic(final String filePath, final String url, final String userAgent, final String referer, final String cookie, final DownFinishListener downFinishListener) {
public static void downMp4(String path , String url, String userAgent, String referer, String cookie, DownFinishListener downFinishListener){
if(path == null) {
String filePath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filePath + File.separator + Environment.DIRECTORY_DOWNLOADS);
if (!file.exists()) {
file.mkdirs();
}
loadPic(file.getPath(), url, userAgent, referer, cookie, downFinishListener, true);
} else {
loadPic(path, url, userAgent, referer, cookie, downFinishListener, true);
}
}
private static void loadPic(final String filePath, final String url, final String userAgent, final String referer, final String cookie, final DownFinishListener downFinishListener, boolean isMp4) {
new AsyncTask<Void,Void,String>(){
String fileName;
InputStream is;
@@ -130,7 +148,9 @@ public class DownPicUtil {
// 提取文件格式真实拓展名
String extension = FormatHelper.getExtension(picFile);
if (isMp4) {
extension = "mp4";
}
// 提取不包含拓展名的原文件名
String[] extensions = fileName.split("\\.");
int splitLength = extensions.length;
@@ -46,33 +46,12 @@ public class PermissionHelper {
public static void CheckPermissions(final Context context, final CheckPermissionListener checkPermissionListener, String... permissionName) {
if (hasPermissions(context, permissionName)) {
// if (hasPermissions(context, permissionName)) {
if (checkPermissionListener != null) {
checkPermissionListener.onAllGranted(true);
}
}else {
// AndPermission.with(context)
// .runtime()
// .permission(permissionName)
// .onGranted(new Action<List<String>>() {
// @Override
// public void onAction(List<String> permissions) {
// // 权限申请成功回调
// if (checkPermissionListener != null) {
// checkPermissionListener.onAllGranted(false);
// }
// }
// })
// .onDenied(new Action<List<String>>() {
// @Override
// public void onAction(List<String> permissions) {
// if (checkPermissionListener != null) {
// checkPermissionListener.onPartlyGranted(permissions, false);
// }
// }
// })
// .start();
}
// }else {
// }
}
}