许可java.lang.nullpoInterException:尝试调用虚拟方法' android.content.context android.content.content.context.getApplicationContext()'

发布于 2025-01-27 08:43:27 字数 5988 浏览 0 评论 0原文

我正在为设置许可而运行一个错误。我在清单中声明了位置和Internet权限,并称为checkpermission()onRequestpermissionsresult以显示权限对话框。但是,我无法启动我的应用程序,并且正在收到相同的错误。

我尝试了

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

上面的行的上下文作为ApplicationContext,此@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])
        }
    }
}
}

I am runnning an error about setting permission. I declared location and internet permissions in my Manifest and called checkPermission() and onRequestPermissionsResult to display permission dialog. However, I can not start my application and am receiving the same error.

I have tried

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

I changed context of the line above as applicationContext, this@MainActivity, MainActivity@This, but I still receive the same error.

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])
        }
    }
}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

趴在窗边数星星i 2025-02-03 08:43:27

在调用ongreate之前,没有初始化活动。这意味着您在此之前不能使用诸如getApplicationContext之类的功能。基本上,活动绝不能具有初始化。如果它们依赖于上下文,他们应该在ongreate中运行所有内容。

Activities aren't initialized until onCreate is called. This means you can't use functions like getApplicationContext until then. Basically, Activities should never have init blocks. They should run everything in onCreate if it relies on a Context.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文