判断context的归属

当需要根据是那个activity的context来进行不同的逻辑处理时,可以将context强转成activity来判断:

try {
    Activity activity = (Activity)context;
} catch (Exception e) {
    e.printStackTrace();
    //说明是ApplicationContext
}
 
if((activity  instanceof HomeActivity){
    //TODO 
}

Kotlin的情况:

try {
    val activity = context as Activity
    if (activity is SplashActivity) {
           return
       }
   } catch (e: Exception) {
       e.printStackTrace();
       //说明是ApplicationContext
   }
    原文作者:Qin0821
    原文地址: https://www.jianshu.com/p/5485c3abd00b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞