Java tutorial
//package com.java2s; //License from project: Apache License import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.RunningTaskInfo; import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; public class Main { /** * whether application is in background * <ul> * <li>need use permission android.permission.GET_TASKS in Manifest.xml</li> * </ul> * * @param context * @return if application is in background return true, otherwise return * false */ public static boolean isApplicationInBackground(Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> taskList = am.getRunningTasks(1); if (taskList != null && !taskList.isEmpty()) { ComponentName topActivity = taskList.get(0).topActivity; if (topActivity != null && !topActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; } /** * Gets the Package Name * * @return */ public static String getPackageName(Context context) { PackageManager p = context.getPackageManager(); // GetPackageName () is your current class package name, 0 stands for is // to get version information PackageInfo packInfo; try { packInfo = p.getPackageInfo(context.getPackageName(), 0); return packInfo.packageName; } catch (NameNotFoundException e) { e.printStackTrace(); return ""; } } }