当需要根据是那个activity的context来进行不同的逻辑处理时,可以将context强转成activity来判断:
1、Java类型判断
try {
Activity activity = (Activity)context;
} catch (Exception e) {
e.printStackTrace();
//说明是ApplicationContext
}
if((activity instanceof HomeActivity){
//TODO
}
2、Kotlin类型判断:
try {
val activity = context as Activity
if (activity is SplashActivity) {
return
}
} catch (e: Exception) {
e.printStackTrace();
//说明是ApplicationContext
}
//简写
open class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (this is MainActivity) {
Log.d("LUO", "===MainActivity===")
} else if (this is TwoActivity) {
Log.d("LUO", "===TwoActivity===")
}
}
}
网友评论