简体   繁体   中英

Android (Kotlin) Context Usage

I've been researching various methods on how to access an activity's context, with mixed results. One concept I came across was creating a global context variable in the 'mainActivity' class. See the GitHub writeup below:

https://gist.github.com/paraya3636/bf8108a75eb49323e56c0c90dd0747e0

This seems very appealing and I'm certain it would work for each time I need to access my context. My question, is if this is proper and encouraged, or something to be avoided? Are there pitfalls and dangers in doing this? Or, perhaps it's situational and really depends on what the app's purpose is?

To sum it up, I'm looking for an experienced answer on how to handle context, when to access it, and how to access it (just high level suggestions). I've taken many Android tutorials and have accessed/used contexts many times, but I really would like to improve my comprehension on the topic and learn from others who are far more versed in Kotlin Android development than I am. I just feel like I'm winging it often times; I'd rather UNDERSTAND it and become a better developer as a result.

Thanks in advance!

If you follow the link it is used the application context. There are two types of context ApplicationContext and ActivityContext , both have the super class Context .

ActivityContext represent the current activity information and it life cycle is depend upon ActivityLifecycle .

ApplicationContext's if you need a context whose lifecycle is separate from the current activity than only you have to use this.

If you want to start any service or the functionality which is not depend on activity life cycle than you can used applicationContext .

If you want to show dialog or startActivity you can used activityContext .

You can get the applicationContext in activity(Kotlin):- this@ActivityName.application

You can get the activityContext in activity(Kotlin):- this@ActivityName

You can find the context in fragment(Kotlin):- activity or context

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