gpt4 book ai didi

java - 如何从 url 下载 pdf 到内部存储并打开它 : Android studio using kotlin

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:47 25 4
gpt4 key购买 nike

class Eco9 : AppCompatActivity() {

lateinit internal var uri: Uri

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_eco9)
this.getActionBar();
this.supportActionBar!!.title = "Class 9th Economics";

fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
supportActionBar?.setDisplayHomeAsUpEnabled(true)

val openActivityDownload: Button = findViewById(R.id.eco9ch1)
openActivityDownload.setOnClickListener {
val s = "https://drive.google.com/file/d/0B71LXrqWr0mFUTk5WnVyVEQ3MFE/export?format=pdf"
val fname = "123.pdf"
if (FileExists(fname)) { previewpdf(fname) }
else { download(s)
Toast.makeText(applicationContext, "File will download", Toast.LENGTH_LONG).show()
}
}

}

fun FileExists(name: String): Boolean {
val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path + separator + name)
return file.exists()
}

private fun download(s: String) {
val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(s)
val request = DownloadManager.Request(uri)
val nameOfFile = URLUtil.guessFileName(uri.toString(), null, MimeTypeMap.getFileExtensionFromUrl(uri.toString()))
val destinationInExternalPublicDir = request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS)
request.setAllowedOverMetered(true)
request.setAllowedOverRoaming(true)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
request.allowScanningByMediaScanner()
downloadManager.enqueue(request)
}

private fun previewpdf(name: String) {
val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path + separator + name)
val path = fromFile(file)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val intent = Intent(Intent.ACTION_VIEW, path)

val chooser = Intent.createChooser(intent, "Open with")
if (intent.resolveActivity(packageManager) != null)
startActivity(chooser)
else
Toast.makeText(applicationContext, "No suitable application to open file", Toast.LENGTH_LONG).show()
}
}

我想从给定的网址下载 pdf,我按下名为“echo9ch1”的按钮,如果内部公共(public)下载文件夹中不存在文件,则调用函数下载,否则如果存在,则应打开 pdf,而不是再次下载。我哪里失踪了?我可以打开之前下载的123.pdf。但我删除了我的 pdf 文件,并且下载功能现在无法使用。实际上,出现了一个小问题,因为我正在使用下载函数中的代码。请帮助我使用 download() 函数,并查看 Preview() 和 fileExists() 函数。我还在manifest.xml中添加了权限。我也想在没有wifi的情况下下载pdf。

list 权限是:

 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

最佳答案

要下载,您必须使用异步任务。

就像在这个例子中一样,我正在下载多个文件,它可以是 PDF、图像等

class DownloadFileAsync(paths: Array<String?>, listener: AsyncResponse?, size: Int) : AsyncTask<String, String, Array<String?>>() {
private val listener: AsyncResponse? = listener
var current = 0
var paths: Array<String?>
val downPaths = arrayOfNulls<String>(size)

lateinit var fpath: String
var show = false


init {
this.paths = paths
}


protected override fun onPreExecute() {
super.onPreExecute()
}

protected override fun doInBackground(vararg aurl: String): Array<String?> {
val rows = aurl.size
while (current < rows) {
var count: Int
try {
println("Current: " + current + "\t\tRows: " + rows)
fpath = getFileName(this.paths[current]!!)
val url = URL(this.paths[current])
val conexion = url.openConnection()
conexion.connect()
val lenghtOfFile = conexion.getContentLength()
val input = BufferedInputStream(url.openStream(), 512)
val file = File(Environment.getExternalStorageDirectory().path.plus(File.separator).plus(fpath))
downPaths.set(current, file.absolutePath)
if (!file.exists()) file.createNewFile()
val output = FileOutputStream(file)
val data = ByteArray(512)
var total: Long = 0
while (true) {
count = input.read(data)
if (count == -1) break
total += count
output.write(data, 0, count)
}


show = true
output.flush()
output.close()
input.close()
current++
} catch (e: Exception) {
Log.d("Exception", "" + e)
}
} // while end
onPostExecute(downPaths)
return downPaths
}

override fun onProgressUpdate(progress: Array<String?>) {

}

override fun onPostExecute(result: Array<String?>) {
listener?.processFinish(result)
}

private fun getFileName(wholePath: String): String {
var name: String? = null
val start: Int
val end: Int
start = wholePath.lastIndexOf('/')
end = wholePath.length //lastIndexOf('.');
name = wholePath.substring((start + 1), end)
return name
}
}

之后我通过接口(interface)回调文件路径 监听器?.processFinish(结果)

关于java - 如何从 url 下载 pdf 到内部存储并打开它 : Android studio using kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50912521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com