Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

android - How to detected if application is closed

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;
}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...