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;
}
}
I had the exact same question , and I was stuck on it for days. Luckily, on day 3, I found a solution that works.
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!