原文地址:
Android开发中,有时候需要判断App是否在前台运行。
代码实现如下:
- private boolean isRunningForeground (Context context)
- {
- ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
- ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
- String currentPackageName = cn.getPackageName();
- if(!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(getPackageName()))
- {
- return true ;
- }
- return false ;
- }
注意:
AndroidManifest.xml中需增加
< uses-permission android:name =“android.permission.GET_TASKS” />