权限 java.lang.NullPointerException:尝试调用虚拟方法 'android.content.Context android.content.Context.getApplicationContext()'

Permission java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()'

我在运行有关设置权限的错误。我在我的清单中声明了位置和互联网权限,并调用 checkPermission()onRequestPermissionsResult 来显示权限对话框。但是,我无法启动我的应用程序并收到同样的错误。

I have tried

private val hasFineLocationPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)

我把上面那行的context改成了applicationContext,this@MainActivity,MainActivity@This,但是还是报同样的错误。

MainActivity

class MainActivity : AppCompatActivity() {

private lateinit var binding : ActivityMainBinding

private var REQUIRED_PERMISSIONS = arrayOf<String>(
    Manifest.permission.ACCESS_FINE_LOCATION,
    Manifest.permission.ACCESS_BACKGROUND_LOCATION)

private val context : Context = applicationContext
private val hasFineLocationPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
private val hasBackgroundLocationPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION)

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

    checkPermission()
}

fun checkPermission() {
    if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED
    ) {
        // Fine Location permission is granted
        // Check if current android version >= 11, if >= 11 check for Background Location permission
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (hasBackgroundLocationPermission == PackageManager.PERMISSION_GRANTED
            ) {
                // Background Location Permission is granted so do your work here
            } else {
                // Ask for Background Location Permission
                askPermissionForBackgroundUsage()
            }
        }
    } else {
        // Fine Location Permission is not granted so ask for permission
        askForLocationPermission();
    }
}

private fun askForLocationPermission() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity,
            Manifest.permission.ACCESS_FINE_LOCATION)
    ) {
        AlertDialog.Builder(this)
            .setTitle("Permission Needed!")
            .setMessage("Location Permission Needed!")
            .setPositiveButton("OK", DialogInterface.OnClickListener { dialogInterface, int ->
                ActivityCompat.requestPermissions(this@MainActivity, arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION), hasFineLocationPermission)
            })
            .setNegativeButton("CANCEL", DialogInterface.OnClickListener { dialogInterface, int ->
                // Permission is denied by the user
                throw RuntimeException("denied")
            })
            .create().show()
    } else {
        ActivityCompat.requestPermissions(this,
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), hasFineLocationPermission)
    }
}

private fun askPermissionForBackgroundUsage() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION)
    ) {
        AlertDialog.Builder(this)
            .setTitle("Permission Needed!")
            .setMessage("Background Location Permission Needed!, tap \"Allow all time in the next screen\"")
            .setPositiveButton("OK", DialogInterface.OnClickListener { dialogInterface, int ->
                ActivityCompat.requestPermissions(this@MainActivity,
                    arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION), hasBackgroundLocationPermission)
            })
            .setNegativeButton("CANCEL", DialogInterface.OnClickListener { dialogInterface, int ->
                // Permission is denied by the user
                throw RuntimeException("denied")
            })
            .create().show()
    } else {
        ActivityCompat.requestPermissions(this,
            arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION), hasBackgroundLocationPermission)
    }
}

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

 //        if (requestCode == PERMISSIONS_REQUEST_CODE && grantResults.size == 
   REQUIRED_PERMISSIONS.size) {
    if (requestCode ==  hasFineLocationPermission) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                if (hasBackgroundLocationPermission == PackageManager.PERMISSION_GRANTED) {
   //                        var check_result = true
   //                        for (result in grantResults) {
   //                            if (result != PackageManager.PERMISSION_GRANTED) {
   //                                check_result = false;
   //                                break;
   //                            }
  //                        }
                } else {
                    askPermissionForBackgroundUsage()
                }
            }
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    REQUIRED_PERMISSIONS[0])
            ) {
                Toast.makeText(this,
                    "denied",
                    Toast.LENGTH_SHORT).show()
                finish()
            } else {
                Toast.makeText(this, "denied", Toast.LENGTH_SHORT)
                    .show()
            }
        }
    } else if (requestCode == hasBackgroundLocationPermission) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // User granted for Background Location Permission.
        } else {
            ActivityCompat.shouldShowRequestPermissionRationale(this,
                REQUIRED_PERMISSIONS[1])
        }
    }
}
}

在调用 onCreate 之前,活动不会被初始化。这意味着您在此之前不能使用像 getApplicationContext 这样的函数。基本上,Activity 永远不应该有 init 块。他们应该 运行 onCreate 中的所有内容,如果它依赖于上下文。