我在后台服务中有一个计时器。它广播一个意图,在活动onReceive()
中收到
我想启动应用程序,如果它被用户杀死。否则我想继续使用该应用程序。我正在使用以下代码从onReceive()
重启应用程序。
if(/*Application is killed*/) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
应该在if
块中使用哪种条件?
答案 0 :(得分:2)
您只需要在接收时检查您的应用程序是否正在运行
代码段
boolean isApplicationRunning = false;
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("com.me.checkprocess")){
Log.e("Result", "App is running - Doesn't need to reload");
isApplicationRunning = true;
break;
}
else
{
Log.e("Result", "App is not running - Needs to reload);
}
}
然后您可以执行
if(isApplicationRunning) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
答案 1 :(得分:0)
要检查您的应用程序是否正在运行,您可以执行以下操作: -
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);
}
答案 2 :(得分:0)
我不知道这是否正确,但以下代码对我有效。
private boolean isApplicationAlive(Context context) {
boolean applicationAlive = false;
ActivityManager m = (ActivityManager) context.getSystemService( context.ACTIVITY_SERVICE );
List<ActivityManager.RunningTaskInfo> runningTaskInfoList = m.getRunningTasks(10);
Iterator<ActivityManager.RunningTaskInfo> itr = runningTaskInfoList.iterator();
while(itr.hasNext()){
ActivityManager.RunningTaskInfo runningTaskInfo = (ActivityManager.RunningTaskInfo)itr.next();
String activityName = runningTaskInfo.topActivity.getShortClassName();
if(activityName.equalsIgnoreCase(".activities.MainActivity")) {
applicationAlive = true;
}
}
return applicationAlive;
}