Я не могу загрузить какие-либо мысли из приложения, в чем проблема, можете ли вы мне помочь.
Хотя я добавил правильность загрузки, но пока не могу загрузить все из приложения. Когда я добавляю ссылку на скачивание в файл, я получаю следующую ошибку «невозможно загрузить файл. Необходимые привилегии недоступны»
Кроме того, я не могу завершить покупки с сайта
примечание к приложению - Webview в Kotlin на Android Studio 3.5.1,
Код ниже взят из файла MainActivity.kt
Спасибо.
package
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.KeyEvent
import android.webkit.*
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.MobileAds
class MainActivity : AppCompatActivity() {
lateinit var mAdView : AdView
lateinit var webView: WebView
lateinit var context: Context
lateinit var activity: Activity
lateinit var downloadListener: DownloadListener
var writeAccess = false
/** Permission Request Code */
private val PERMISSION_REQUEST_CODE = 1234
/** Sample Page from which we will download the file */
private val downloadPage = "https://mrshoping.com/"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
getSupportActionBar()?.hide(); /* hide the title bar */
setContentView(R.layout.activity_main)
MobileAds.initialize(this, "ca-app-pub-")
mAdView = findViewById(R.id.adView)
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest)
/** Application Context and Main Activity */
context = applicationContext
activity = this
/** Initialize main layout and web view */
webView = findViewById(R.id.webView)
/** Check permission to write in external storage */
checkWriteAccess()
/** Create a Download Listener */
createDownloadListener()
/** Display Toast Message When Download Complete */
onDownloadComplete()
/** Configure Web View */
configureWebView()
}
private fun onDownloadComplete()
{
/** Code that receives and handles broadcast intents sent by Context.sendBroadcast(Intent) */
val onComplete = object : BroadcastReceiver() {
override fun onReceive(ctxt: Context, intent: Intent) {
Toast.makeText(context,"File Downloaded",Toast.LENGTH_LONG).show()
}
}
/** Register to receives above broadcast */
registerReceiver(onComplete, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@SuppressLint("SetJavaScriptEnabled")
private fun configureWebView()
{
/** Web View General Setup */
webView.webViewClient = MyWebViewClient()
/** We will use it to enable the Java Script Support. */
webView.settings.javaScriptEnabled = true
/** loadUrl : Loads the given URL. */
webView.loadUrl(downloadPage)
/** File Download Listener */
webView.setDownloadListener(downloadListener)
}
private inner class MyWebViewClient : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return true
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
view.loadUrl(request.url.toString())
return true
}
}
private fun createDownloadListener()
{
downloadListener = DownloadListener { url, userAgent, contentDescription, mimetype, contentLength ->
val request = DownloadManager.Request(Uri.parse(url))
request.allowScanningByMediaScanner()
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
val fileName = URLUtil.guessFileName(url, contentDescription, mimetype)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
val dManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
if(writeAccess)
dManager.enqueue(request)
else
{
Toast.makeText(context,"Unable to download file. Required Privileges are not available.",Toast.LENGTH_LONG).show()
checkWriteAccess()
}
}
}
private fun checkWriteAccess()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
/**
* Check for permission status.
* */
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE))
{
val builder = AlertDialog.Builder(activity)
builder.setMessage("Required permission to write external storage to save downloaded file.")
builder.setTitle("Please Grant Write Permission")
builder.setPositiveButton("OK") { _, _->
ActivityCompat.requestPermissions(
activity,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
PERMISSION_REQUEST_CODE
)
}
builder.setNeutralButton("Cancel", null)
val dialog = builder.create()
dialog.show()
} else {
ActivityCompat.requestPermissions(
activity,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
PERMISSION_REQUEST_CODE
)
}
}
else {
/**
* Already have required permission.
* */
writeAccess = false
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSION_REQUEST_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
writeAccess=true
} else {
// Permission denied
writeAccess=false
Toast.makeText(context,"Permission Denied. This app will not work with right permission.",Toast.LENGTH_LONG).show()
}
}
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
webView.goBack() // Go to previous page
return true
}
// Use this as else part
return super.onKeyDown(keyCode, event)
}
}