要检查您的应用程序是否正在运行,您可以做的是:-
if(isProcessRunning("package_name")) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
public boolean isProcessRunning(String process) {
ActivityManager activityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
for(int i = 0; i < procInfos.size(); i++){
if (procInfos.get(i).processName.equals(process)) {
return true;
}
}
return false;
}
试试这个它会工作。
如果您的应用程序只有一个或两个活动,或者如果您的应用程序有一个由其他活动扩展的 BaseActivity,请执行以下操作:-
public class MyApplication extends Application{
private static boolean mIsRunning = false;
public static boolean isRunning(){
return mIsRunning;
}
public void setRunning(boolean isRunning){
mIsRunning = isRunning;
}
}
从您的活动中:-
public void onCreate(Bundle savedInstanceState){
MyApplication.setRunning(true);
}
public void onDestroy(){
MyApplication.setRunning(false);
}
你可以像这样检查: -
if(!MyApplication.isRunning()) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}