前后台切换进行展示广告通过监听app的切换的方式进行实现
通过ActivityManager.RunningAppProcessInfo判断进行监听应用
可以在MainActivity进行测试,然后在MainActivity的onResume()和onStop()方法中进行判断应用程序是否进入到后台并且是否从后台返回到了前台
@Override
protected void onStart() {
super.onStart();
if (!isCurrentRunningForeground) {
isCurrentRunningForeground=true;
//这里进行广告处理的实现方法
jysdk.jyyouSDKInit(MainActivity.this, new JYkhfController.JYAdCallback() {
@Override
public void result(Integer code) {
JYkhfController.shareInstance().showSplashView();
}
});
Log.e(TAG, ">>>>>>>>>>>>>>>>>>>切回前台 activity process");
}
}
@Override
protected void onStop() {
super.onStop();
isCurrentRunningForeground = isRunningForeground();
if (!isCurrentRunningForeground) {
Log.e(TAG,">>>>>>>>>>>>>>>>>>>切到后台 activity process");
}
}
public boolean isRunningForeground() {
ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager.getRunningAppProcesses();
// 枚举进程,查看该应用是否在运行
for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos) {
if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (appProcessInfo.processName.equals(this.getApplicationInfo().processName)) {
Log.e(TAG,"EntryActivity isRunningForeGround");
return true;
}
}
}
Log.e(TAG, "EntryActivity isRunningBackGround");
return false;
}
看看运行效果如下:
03-24 11:15:26.488 30482-30482/adlog: >>>>>>>>>>>>>>>>>>>切到后台 activity process
03-24 11:16:12.438 30482-30482/adlog: >>>>>>>>>>>>>>>>>>>切回前台 activity process