我的应用程序从Broadcastreceiver接收,以便在我的应用程序运行时从网络(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 tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(mContext.getPackageName())) {
return false;
}
}
return true;
}
}