如何检测应用程序是否关闭 [英] How to detected if application is closed

查看:276
本文介绍了如何检测应用程序是否关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,当我的应用程序在获取时运行时,它会从Broadcastreceiver接收以从web(json)获取新数据;一切运行良好,当应用程序关闭时,它崩溃了您的应用程序停止工作".即使以下检查我的应用程序是否在前台的商品也无法正常工作. 我想要它,如果该应用程序是关闭的而不是正在运行,则调用它来打开应用程序以使其不会崩溃,那么如何检查应用程序是否已关闭?

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?

我的代码;

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

}

推荐答案

我遇到了完全相同的问题,并且在时被卡住了.幸运的是,在第3天,我找到了一个可行的解决方案.

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
}

onTrimMemory方法非常有用.应该使用它来优化您的内存中的应用程序,但是我们也可以像这样利用它来发挥我们的优势!

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!

这篇关于如何检测应用程序是否关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆