2

我有一个应用程序,它从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; 
} 

}

+0

从设备中添加崩溃日志 –

+0

不打印 – MadBoy

+0

也许有些时候我的Android工作室有问题? – MadBoy

回答

3

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

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

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

+0

哈哈感谢兄弟,但我把它作为参数传递? – MadBoy

+0

好的,我把它标记为我的朋友,那么我在哪里调用这个方法?在我的OnRecieve()?然后我在哪里打电话给我的意图? – MadBoy

+0

@MadBoy你不需要叫它!这是一个很酷的部分,它就像一个听众。只要用户离开,它就会自动调用! –