我有一個應用程序,它從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;
}
}
從設備中添加崩潰日誌 –
不打印 – MadBoy
也許有些時候我的Android工作室有問題? – MadBoy