如何区分给定的Context对象是Activity还是Service Context?

Mic*_*udy 17 android

我想知道我的给定Context对象是来自Activity,Service还是Application.或者换句话说,如果我的代码在后台或前台执行.(前景是指活动代码和活动创建的线程.)

dan*_*h32 46

您应该能够使用"instanceof"测试对象是否是特定类

if (context instanceof Activity) {
  // handle activity case
} else if (context instanceof Service){
  // handle service case
}
Run Code Online (Sandbox Code Playgroud)