Kotlin如何使用辅助构造函数进行扩展

时间:2019-10-10 06:08:47

标签: kotlin

我有一个帮助器类来获取网络更新。当我尝试创建辅助构造函数时会抛出错误 基于kotlin中的文档,我需要扩展超类。但是我得到同样的错误。 根据文档,ConnectivityManager没有构造函数

我收到此错误

Supertype initialization is impossible without primary constructor

我的助手班

class InternetConnectivityHelper : ConnectivityManager.NetworkCallback() {

    constructor(context: Context, internetStatusChangedListener: InternetStatusChangedListener): super(){

    }
}

我还尝试了基于stackoverflow答案之一

class InternetConnectivityHelper : ConnectivityManager.NetworkCallback() {

    constructor(context: Context, internetStatusChangedListener: InternetStatusChangedListener): this(){

    }
}

我也看过本教程,但似乎无法使它正常工作 https://www.youtube.com/watch?v=DmSLv-fX8PA&list=PLlxmoA0rQ-LwgK1JsnMsakYNACYGa1cjR&index=40

2 个答案:

答案 0 :(得分:1)

原因是根据文档,requestedPermissions可以为空。

/**
 * Array of all {@link android.R.styleable#AndroidManifestUsesPermission
 * <uses-permission>} tags included under <manifest>,
 * or null if there were none.  This is only filled in if the flag
 * {@link PackageManager#GET_PERMISSIONS} was set.  This list includes
 * all permissions requested, even those that were not granted or known
 * by the system at install time.
 */
public String[] requestedPermissions;

但是您的permissionList变量是null安全的-您不能将null分配给null安全的变量。

UPD:尝试使用此代码(添加了null检查并用列表替换了数组)

object RuntimePermissionUtil {
private var permissionList = mutableListOf<String>()

fun retrivePermissionList(context: Context) : List<String>{

    context.getPackageManager().getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS).requestedPermissions?.let {
        permissionList.clear()
        permissionList.addAll(it)
    }

    //your other stuff

    return permissionList
}
}

答案 1 :(得分:0)

我设法通过初始化以下值来解决它

object RuntimePermissionUtil {

    private var permissionList : Array<String> = emptyArray()

    fun RetrivePermissionList(context: Context) : Array<String>{

        if(context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS).requestedPermissions != null){
            permissionList = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS).requestedPermissions
        }

        if(LogConfiguration.RuntimePermissionEnabled){
            LogUtil.LOGD(LogConfiguration.RuntimePermission, "RetrievePermissionList : "+ permissionList.contentToString())
        }

        return permissionList
    }
}