Android回调和代码重用

时间:2017-11-10 11:34:39

标签: android kotlin

在一个片段中,我有一个下载代码。而且我确定我也需要其他片段中的下载功能。

所以我想从片段中将它作为一个独立的文件库,但是代码包含一些堆叠在Activity上的android回调方法,如果我将它移动到另一个文件,我不知道如何处理它(Class )。

片段中的下载代码

private fun beforeDownload() {
    // check permission
    val externalPermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
    if (externalPermission != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_ID_STORAGE_PERMISSION)
    } else {
        onDownload()
    }
}

/** Android call-back method after requesting permission **/
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    beforeDownload()
}


private fun onDownload() {
    if (media >= 100000000) {
        Toast.makeText(activity, "The media is over 100Mb", Toast.LENGTH_SHORT).show()
    } else {
        downloadMediaJob = launch(UI) { downloadMedia() }
    }
}

// Android receiver when download completed
private val onDownloadComplete = object : BroadcastReceiver() {
    override fun onReceive(p0: Context?, p1: Intent?) {
        Toast.makeText(activity, R.string.download_complete_msg, Toast.LENGTH_SHORT).show()
    }
}

suspend private fun downloadMedia() {
    downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    ...
    downloadedFileId = downloadManager.enqueue(request)
}

并且回调方法是

onRequestPermissionsResult

onDownloadComplete

如何将它们移动到MediaDownload类以使其可重复使用?

1 个答案:

答案 0 :(得分:0)

每个片段需要来实现它自己的生命周期回调,但该回调可以简单地委托给对象实例上的方法。

例如,在上面的代码中:

private fun beforeDownload() {
    // check permission
    val externalPermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
    if (externalPermission != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_ID_STORAGE_PERMISSION)
    } else {
        onDownload()
    }
}

/** Android call-back method after requesting permission **/
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    beforeDownload()
}

你应该将beforeDownload()方法移动到某些&#34; model&#34;类,创建或注入实例,然后在该实例上调用beforeDownload()方法。

class SomeModel() {
   fun beforeDownload() {
      ...
   }
}

每个Fragment仍然需要生命周期方法,但代码的主要部分可以在SomeModel类中共享

override fun onRequestPermissionsResult(requestCode: Int, permissions: 
    Array<out String>, grantResults: IntArray) {
    instanceOfSomeModel.beforeDownload()
}

完成删除必须实现最小生命周期方法的冗余的唯一方法是将子类化为子类,并在子类中的覆盖中添加您的方法调用,但是您不希望去做!