package cn.testforeground;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
/**
* Demo描述:
* 判断当前应用是否在前台运行
*
* 注意权限:
* <uses-permission android:name ="android.permission.GET_TASKS" />
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
isRunningForeground();
}
public boolean isRunningForeground(){
String packageName=getPackageName(this);
String topActivityClassName=getTopActivityName(this);
System.out.println("packageName="+packageName+",topActivityClassName="+topActivityClassName);
if (packageName!=null&&topActivityClassName!=null&&topActivityClassName.startsWith(packageName)) {
System.out.println("---> isRunningForeGround");
return true;
} else {
System.out.println("---> isRunningBackGround");
return false;
}
}
public String getTopActivityName(Context context){
String topActivityClassName=null;
ActivityManager activityManager =
(ActivityManager)(context.getSystemService(android.content.Context.ACTIVITY_SERVICE )) ;
List<RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1) ;
if(runningTaskInfos != null){
ComponentName f=runningTaskInfos.get(0).topActivity;
topActivityClassName=f.getClassName();
}
return topActivityClassName;
}
public String getPackageName(Context context){
String packageName = context.getPackageName();
return packageName;
}
}
项目需要研究,通知栏进入程序,技术点有判断当前程序是否在前台运行。上网搜到该帖。