How to detected if application is closed

[亡魂溺海] 提交于 2019-12-18 05:16:10

问题


I have an app that receives from the Broadcastreceiver to fetch new data from the web(json), when my app is running while it fetches; everything runs well, when the app is closed it crashes "Your app stopped working". Even the following good to check if my app is in the foreground doesn't work. i want it so if the app is closed, not running, to call an intent to open the app for it not to crash, so how do I check if application is closed?

My code;

public class UpdateReceiver extends BroadcastReceiver {

private static long alarmTime = 0;

@Override
public void onReceive(Context context, Intent intent) {



    if (isAppForground(context)){
        Toast.makeText(context, "APP IN FOREGROUND", Toast.LENGTH_LONG).show();
    } else {
        Intent intentActivity = new Intent(context, MainActivity.class);
        intentActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intentActivity);
        Toast.makeText(context, "APP NOT RUNNING", Toast.LENGTH_LONG).show();
    }

    //set new alarm for next tuesday
    UpcomingFragment.getInstance().setAlarm(-1);
    //updates the current json
    UpcomingFragment.getInstance().update();


}

public static long getAlermTimeInMillis(){
    return alarmTime;
}

public boolean isAppForground(Context mContext) {

    ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(mContext.getPackageName())) {
            return false;
        }
    }

    return true;
}

}


回答1:


I had the exact same question , and I was stuck on it for days. Luckily, on day 3, I found a solution that works.

public void onTrimMemory(final int level) {
    if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
        //SCREEN IS NOT SHOWING
}

This onTrimMemory method is extremely useful. It is supposed to be used to optimize your app in memory, but we can use it to our advantage like this also!



来源:https://stackoverflow.com/questions/33818406/how-to-detected-if-application-is-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!