简体   繁体   中英

Should I use getApplicationContext() or getContext() in Intent?

On button click I'm starting a new activity like this:

        Intent(requireContext(), SecondActivity::class.java).apply {
        putExtra(RECORDED_SUCCESSFULLY, filePath)
        (activity as FirstActivity).finish()
        startActivity(this)
        }

But because I need to finish this activity before creating a new one, requireContext() here will be occasionally equal null and this causes a crash. So my question is, can I use getApplicationContext() or should I use safe call with getContext() in this situation?

It's prefered to use Activityname.this or getApplicationContext(). Remember there are two types of contexts in android and when you are dealing with activity components such as finish use Activityname.this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM