【问题标题】:How to detected if application is closed如何检测应用程序是否关闭
【发布时间】:2015-11-20 03:19:07
【问题描述】:

我有一个应用程序从 Broadcastreceiver 接收以从 web(json) 获取新数据,当我的应用程序在获取时运行;一切运行良好,当应用程序关闭时它崩溃“你的应用程序停止工作”。即使是以下检查我的应用程序是否在前台的好方法也不起作用。 我想要它,所以如果应用程序已关闭,未运行,则调用意图打开应用程序以使其不会崩溃,那么如何检查应用程序是否已关闭?

我的代码;

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

}

【问题讨论】:

  • 从设备添加崩溃日志
  • 也许我的 Android 工作室有时出了问题?
  • 使用此命令将其保存在文件 adb logcat > crashlogs.txt
  • 我在哪里执行这个命令?

标签: android android-intent broadcastreceiver android-broadcast


【解决方案1】:

我有完全相同的问题,我被困了 。幸运的是,在第 3 天,我找到了一个可行的解决方案。

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

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

【讨论】:

  • 好的,我把它标记为我的朋友,那么我在哪里调用这个方法呢?在我的 OnRecieve() 中?然后我在哪里调用我的意图?
  • @MadBoy 你不需要打电话!这是很酷的部分,它就像一个听众。一旦用户离开,它就会被自己调用!
  • 如果它返回“true”那意味着应用程序正在运行或关闭?
  • @MadBoy 它不返回布尔值。相反,我们像这样比较它:level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
  • 它只有在应用程序完全从内存堆栈中删除时才有效,如果它被隐藏但仍在内存堆栈中怎么办,我在 Lollipop 和 Nougat OS 上测试你的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 2017-07-23
  • 2012-05-10
  • 2015-03-22
相关资源
最近更新 更多