我想检查我的应用程序是在后台还是在前台,我还想使用BroadcastReceiver检查应用程序是否处于打开状态

public class CheckRunningApplicationReceiver extends BroadcastReceiver {
Context mContext;

public int mId = 1000;
NotificationManager mNotificationManager;

@Override
public void onReceive(Context aContext, Intent anIntent) {
    mContext = aContext;
    Boolean isAppOpen = isApplicationSentToBackground(aContext);
    mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    if (isAppOpen) {
        //openNotification();
    } else {
        //mNotificationManager.cancel(mId);
    }

}

private void openNotification() {// Instantiate notification with icon and
                                    // ticker message
    Notification notification = new Notification(R.drawable.ic_launcher,"Notification message!", System.currentTimeMillis());
    PendingIntent i = PendingIntent.getActivity(mContext, 0, new Intent(mContext,MainActivity.class), 0);
    notification.setLatestEventInfo(mContext, "Notification Created","Click here to see the message", i);
    notification.flags = Notification.FLAG_ONGOING_EVENT;
    mNotificationManager.notify(mId, notification);
}

public static boolean isApplicationSentToBackground(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }

    return false;
}

}
有什么解决办法吗,帮帮我,
谢谢。

最佳答案

即使应用程序在后台,广播接收器也可以工作,因为接收器接收到的事件是全局发送的,并且每个应用程序都注册为侦听这些事件,而不管应用程序是否正在运行。
要处理此问题,请在广播接收器的onreceive代码中,检查应用程序是否在前台。
有一个——而且我只知道一个——始终如一地有效地做到这一点。您需要跟踪应用程序的暂停/恢复操作。确保你在每一个活动中都检查这个。
这里有一些示例代码。在您的情况下,您需要在从BroadcastReceiver执行任何操作之前检查myapplication.isActivityVisible()==true作为验证。

09-04 15:23
查看更多