首页 > 解决方案 > 有没有办法使用 Kotlin(不是 Java)将网页下载到本地存储?

问题描述

对于任何想将此问题标记为“重复”的人,请记住,我要求的是 KOTLIN 解决方案,而不是 8 年前的 Java 解决方案。谢谢你。

所以我有这个应用程序,它在 NFC 标签中获取 URL,我希望它下载该网页并将其保存在本地存储中,稍后将在 Webview 中加载。我已经拥有获取 NDEF 消息并将其处理为字符串的功能。我遵循了一些 Java 教程并使用 J2K 转换了文件,但似乎没有一个工作,我相信我做错了什么,但我似乎无法在这里或谷歌上找到解决方案。我曾尝试将 URL 记录到控制台,但我想我也做错了。

我将把 MainActivity 类留给你:


class MainActivity : AppCompatActivity() {
    // NFC adapter for checking NFC state in the device
    private var nfcAdapter: NfcAdapter? = null

    // Pending intent for NFC intent foreground dispatch.
    // Used to read all NDEF tags while the app is running in the foreground.
    private var nfcPendingIntent: PendingIntent? = null
    // Optional: filter NDEF tags this app receives through the pending intent.
    //private var nfcIntentFilters: Array<IntentFilter>? = null

    private val KEY_LOG_TEXT = "logText"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val instance = Download()
        Log.i("Url download", instance.toString())

        // Restore saved text if available
        if (savedInstanceState != null) {
            dahcor.text = savedInstanceState.getCharSequence(KEY_LOG_TEXT)
        }

        // Check if NFC is supported and enabled
        nfcAdapter = NfcAdapter.getDefaultAdapter(this)
        Log.i("NFC supported", (nfcAdapter != null).toString())
        Log.i("NFC enabled", (nfcAdapter?.isEnabled).toString())


        // Read all tags when app is running and in the foreground
        // Create a generic PendingIntent that will be deliver to this activity. The NFC stack
        // will fill in the intent with the details of the discovered tag before delivering to
        // this activity.
        nfcPendingIntent = PendingIntent.getActivity(this, 0,
                Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)

        // Optional: Setup an intent filter from code for a specific NDEF intent
        // Use this code if you are only interested in a specific intent and don't want to
        // interfere with other NFC tags.
        // In this example, the code is commented out so that we get all NDEF messages,
        // in order to analyze different NDEF-formatted NFC tag contents.
        //val ndef = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
        //ndef.addCategory(Intent.CATEGORY_DEFAULT)
        //ndef.addDataScheme("https")
        //ndef.addDataAuthority("*.andreasjakl.com", null)
        //ndef.addDataPath("/", PatternMatcher.PATTERN_PREFIX)
        // More information: https://stackoverflow.com/questions/30642465/nfc-tag-is-not-discovered-for-action-ndef-discovered-action-even-if-it-contains
        //nfcIntentFilters = arrayOf(ndef)
        Download()
        Download()

        if (intent != null) {
            // Check if the app was started via an NDEF intent
            Log.i("Found intent in onCreate", intent.action.toString())
            processIntent(intent)
        }

        // Make sure the text view is scrolled down so that the latest messages are visible
    }

    override fun onResume() {
        super.onResume()
        // Get all NDEF discovered intents
        // Makes sure the app gets all discovered NDEF messages as long as it's in the foreground.
        nfcAdapter?.enableForegroundDispatch(this, nfcPendingIntent, null, null);
        // Alternative: only get specific HTTP NDEF intent
        //nfcAdapter?.enableForegroundDispatch(this, nfcPendingIntent, nfcIntentFilters, null);
    }

    override fun onPause() {
        super.onPause()
        // Disable foreground dispatch, as this activity is no longer in the foreground
        nfcAdapter?.disableForegroundDispatch(this);
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Log.i("Found intent in onNewIntent", intent?.action.toString())
        // If we got an intent while the app is running, also check if it's a new NDEF message
        // that was discovered
        if (intent != null) processIntent(intent)
    }

    /**
     * Check if the Intent has the action "ACTION_NDEF_DISCOVERED". If yes, handle it
     * accordingly and parse the NDEF messages.
     * @param checkIntent the intent to parse and handle if it's the right type
     */
    private fun processIntent(checkIntent: Intent) {
        // Check if intent has the action of a discovered NFC tag
        // with NDEF formatted contents
        if (checkIntent.action == NfcAdapter.ACTION_NDEF_DISCOVERED) {
            Log.i("New NDEF intent", checkIntent.toString())

            // Retrieve the raw NDEF message from the tag
            val rawMessages = checkIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
            val url = rawMessages
            if (rawMessages != null) {
                Log.i("Raw messages", rawMessages.size.toString())
            }

            // Complete variant: parse NDEF messages
            if (rawMessages != null) {
                val messages = arrayOfNulls<NdefMessage?>(rawMessages.size)// Array<NdefMessage>(rawMessages.size, {})
                for (i in rawMessages.indices) {
                    messages[i] = rawMessages[i] as NdefMessage

                }
                // Process the messages array.
                processNdefMessages(messages)
            }

            // Simple variant: assume we have 1x URI record
            //if (rawMessages != null && rawMessages.isNotEmpty()) {
            //    val ndefMsg = rawMessages[0] as NdefMessage
            //    if (ndefMsg.records != null && ndefMsg.records.isNotEmpty()) {
            //        val ndefRecord = ndefMsg.records[0]
            //        if (ndefRecord.toUri() != null) {
            //            logMessage("URI detected", ndefRecord.toUri().toString())
            //        } else {
            //            // Other NFC Tags
            //            logMessage("Payload", ndefRecord.payload.contentToString())
            //        }
            //    }
            //}

        }
    }

    /**
     * Parse the NDEF message contents and print these to the on-screen log.
     */
    private fun processNdefMessages(ndefMessages: Array<NdefMessage?>) {
        // Go through all NDEF messages found on the NFC tag
        for (curMsg in ndefMessages) {
            if (curMsg != null) {
                // Print generic information about the NDEF message
                Log.i("Message", curMsg.toString())
                // The NDEF message usually contains 1+ records - print the number of recoreds
                Log.i("Records", curMsg.records.size.toString())

                // Loop through all the records contained in the message
                for (curRecord in curMsg.records) {
                    if (curRecord.toUri() != null) {
                        // URI NDEF Tag
                        val url = curRecord.toUri().toString()
                        val intent = Intent(this, Webview::class.java)
                        intent.putExtra("Url", url)
                        startActivity(intent)
                        Log.i("- URI", curRecord.toUri().toString())
                    } else {
                        // Other NDEF Tags - simply print the payload
                        Log.i("- Contents", curRecord.payload!!.contentToString())
                    }
                }
            }
        }
    }
    fun Download(args: Array<String>) {
    val fileName = intent.getStringExtra("Url")
    val url = fileName.toString().trim()

    if(url.toString()!=null && url.toString().trim()!=""){
        val fileOutputStream: FileOutputStream
        try {
            fileOutputStream = openFileOutput(url, Context.MODE_PRIVATE)
        } catch (e: FileNotFoundException){
            e.printStackTrace()
        }catch (e: NumberFormatException){
            e.printStackTrace()
        }catch (e: IOException){
            e.printStackTrace()
        }catch (e: Exception){
            e.printStackTrace()
        }
        Toast.makeText(applicationContext,"data save", Toast.LENGTH_LONG).show()

    }

    fun download(urlString: String?) {
        // Create URL object
        val url = URL(urlString)
        fun writeFileOnInternalStorage(mcoContext: Context, sFileName: String?, sBody: String?) {
            val dir = File(mcoContext.filesDir, "Files")
            if (!dir.exists()) {
                dir.mkdir()
                // Enter filename in which you want to download
                BufferedReader(InputStreamReader(url.openStream())).use { reader ->

                    BufferedWriter(FileWriter("${url}.html")).use { writer ->
                        // read each line from stream till end
                        var line: String?
                        while (reader.readLine().also { line = it } != null) {
                            writer.write(line)
                        }
                        println("Page downloaded.")
                    }
                }
            }
            // Exceptions
            try {
                val gpxfile = File(dir, sFileName)
                val writer = FileWriter(gpxfile)
                writer.append(sBody)
                writer.flush()
                writer.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }




        }}

}
}

标签: androidkotlindownload

解决方案


推荐阅读