android检测是否跳出应用程序,android – 如何检测应用程序是否已关闭

我的应用程序从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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值