如何在kotlin android中调用内部类方法中的Activity类方法

时间:2018-02-28 08:02:53

标签: android kotlin inner-classes

我在Activity类中创建了一个进度方法。然后为AsyncTask创建另一个类。

我的要求是在AsyncTask类中调用 processProgressBar()方法doInBackground()

怎么可能?

请参阅我的代码:

package com.example.bharat.generalknowledge

import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import com.example.bharat.generalknowledge.dbhandler.DatabaseHandler
import org.xml.sax.InputSource
import java.io.BufferedInputStream
import java.io.FileOutputStream
import java.net.URL
import java.util.zip.GZIPInputStream

class WelcomeActivity : AppCompatActivity() {
    init {
        println("Init block")
    }

    companion object {
        var dbPath: String = ""
        var isDatabaseExist: Boolean = false
        private val handler = Handler()
        val wActivity = WelcomeActivity()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_welcome)

        val dbHandler = DatabaseHandler(this)
        isDatabaseExist = dbHandler.checkIfTableExistOrNot()
        Log.w("isDatabaseExist: ", isDatabaseExist.toString())
        if(!isDatabaseExist){
            dbPath = dbHandler.getDatabasePath()
            downloadDb().execute()
        }
    }

    fun processProgressBar(pStatus: Int=10){

        println("====================processProgressBar==========================")
        val res = resources
        val drawable = res.getDrawable(R.drawable.circular)
        val mProgress = findViewById<View>(R.id.circularProgressbar) as ProgressBar
        mProgress.progress = 0   // Main Progress
        mProgress.secondaryProgress = 100 // Secondary Progress
        mProgress.max = 100 // Maximum Progress
        mProgress.progressDrawable = drawable
        mProgress.progress = pStatus
    }

    class downloadDb() : AsyncTask<Void, Void, String>() {

        override fun doInBackground(vararg params: Void?): String? {
            try {
                // download the file
                val url = URL("http://192.168.0.105/new-gk-app/web/uploads/db-backup/gk_app.gz")
                val connection = url.openConnection()
                connection.connect()

                // get stream and convert gzip to db original
                var stream = connection.getInputStream()
                stream = GZIPInputStream(stream)
                val `is` = InputSource(stream)

                val input = BufferedInputStream(`is`.byteStream, 8192)
                val output = FileOutputStream(dbPath)

                val data = ByteArray(1024)
                while ((input.read(data)) != -1) {
                    output.write(data);

                    // processProgressBar(30)  /* ****** my requirement is call this method ******* */
                }
                output.flush()
                output.close()
                input.close()

            } catch (e: Exception) {
                Log.e("Error: ", e.message)
            }
            return null
        }

        override fun onPreExecute() {
            super.onPreExecute()
            Log.w("Database Downloded: ", "Start")
            // ...
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            Log.w("Database Downloded: ", "Finish")
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您可以在Async任务的构造函数中传递活动的引用,包含在弱引用中并从那里调用您的函数。

 class downloadDb(var activity:WeakReference<WelcomeActivity >) : AsyncTask<Void, Void, String>()

和你doInBackground

  activity.get()?.let {
                it.runOnUiThread({

                })
            }

初始化AysncTask,downloadDb(WeakReference(this))

答案 1 :(得分:-1)

当你在后台调用时显示你需要主要ui线程的进度条,因为doInBackground方法调用后台线程那个时候如果想要更新你需要的任何东西主ui线程。 您使用下面的代码显示您的进度条...

class downloadDb() : AsyncTask<Void, Void, String>() {

    override fun doInBackground(vararg params: Void?): String? {
        try {
            // download the file
            val url = URL("http://192.168.0.105/new-gk-app/web/uploads/db-backup/gk_app.gz")
            val connection = url.openConnection()
            connection.connect()

            // get stream and convert gzip to db original
            var stream = connection.getInputStream()
            stream = GZIPInputStream(stream)
            val `is` = InputSource(stream)

            val input = BufferedInputStream(`is`.byteStream, 8192)
            val output = FileOutputStream(dbPath)

            val data = ByteArray(1024)
            while ((input.read(data)) != -1) {
                output.write(data);
                Handler().run {
                    WelcomeActivity().processProgressBar()
                }
                // processProgressBar(30)  /* ****** my requirement is call this method ******* */
            }

            output.flush()
            output.close()
            input.close()

        } catch (e: Exception) {
            Log.e("Error: ", e.message)
        }
        return null
    }

    override fun onPreExecute() {
        super.onPreExecute()
        Log.w("Database Downloded: ", "Start")
        // ...
    }

    override fun onPostExecute(result: String?) {
        super.onPostExecute(result)
        Log.w("Database Downloded: ", "Finish")
    }
}

仅在代码下方添加...

 Handler().run {
                    WelcomeActivity().processProgressBar()
                }