简体   繁体   English

如何检查应用程序是否在BroadcastReceiver中的前台后台运行

[英]How to check app is running in background of foreground in BroadcastReceiver

i want to check whether the my application is in a background or in a Foreground and i also want to check the app in open or not using BroadcastReceiver 我想检查我的应用程序是在后台还是在Foreground中,我还想要打开或不使用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;
}

} }

is there any solution for this, help me , Thanks. 对此有什么解决方案,帮助我,谢谢。

A BroadcastReceiver works even when the app is in the background because the event that the receiver picks up are sent globally, and each app is registered to listen in on these, regardless of whether or not app is running. 即使应用程序处于后台,BroadcastReceiver也能正常工作,因为接收方接收的事件是全局发送的,并且每个应用程序都已注册以监听这些应用程序,无论应用程序是否正在运行。

To deal with this, in your BroadcastReceiver's onReceive code, check if your app is in the foreground. 要处理此问题,请在BroadcastReceiver的onReceive代码中检查您的应用是否位于前台。

There is one--and only one that I know of--consistently effective method to do this. 我知道有一个 - 也是唯一一个 - 持续有效的方法来做到这一点。 You need to keep track of your pause/resume actions for your application. 您需要跟踪应用程序的暂停/恢复操作。 Ensure that you check this in every activity. 确保在每项活动中检查此项。

There is some sample code in this answer . 这个答案中有一些示例代码。 In your case, you would want to check MyApplication.isActivityVisible() == true as a validation before doing anything from your BroadcastReceiver. 在您的情况下,您需要在从BroadcastReceiver执行任何操作之前检查MyApplication.isActivityVisible()== true作为验证。

In your activity register broadcast receiver to check activity is in foreground or background. 在您的活动注册广播接收器中检查活动是在前台还是后台。

StackAnswer.java
public class StackAnswer extends Activity {
    public static final int IS_ALIVE = Activity.RESULT_FIRST_USER;
    public static final String CHECK_ALIVE_ACTION = "CHECK_ALIVE_ACTION";
    private BroadcastReceiver mRefreshReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRefreshReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                Log.i("onReceive","BroadcastIntent received in MainActivity");

                // TODO:                
                // Check to make sure this is an ordered broadcast
                // Let sender know that the Intent was received
                // by setting result code to MainActivity.IS_ALIVE
                setResultCode(MainActivity.IS_ALIVE);
            }
        };
    }



    // Register the BroadcastReceiver
    @Override
    protected void onResume() {
        super.onResume();

        // TODO:
        // Register the BroadcastReceiver to receive a 
        // DATA_REFRESHED_ACTION broadcast
        IntentFilter filter = new IntentFilter();
        filter.addAction(CHECK_ALIVE_ACTION);         
        registerReceiver(mRefreshReceiver, filter);     

    }

    @Override
    protected void onPause() {

        // TODO:
        // Unregister the BroadcastReceiver if it has been registered
        // Note: To work around a Robotium issue - check that the BroadcastReceiver
        // is not null before you try to unregister it
        if(mRefreshReceiver!=null){
            unregisterReceiver(mRefreshReceiver);
        }
        super.onPause();
    }


}

Send broadcast from background to check weather activity is alive or not 从背景发送广播以检查天气活动是否存在

   BackgroundTask.java
   public class BackgroundTask {

    private void checkIfForeground (Context mApplicationContext){
        mApplicationContext.sendOrderedBroadcast(new Intent(
                StackAnswer.CHECK_ALIVE_ACTION), null,
                new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO: Check whether the result code is not MainActivity.IS_ALIVE
                if (getResultCode() != StackAnswer.IS_ALIVE) {
                    //Background 
                }else{
                    //Foreground 
                }
            }
        }, null, 0, null, null);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过BroadcastReceiver在Android中获取前台运行的应用程序 - How to get foreground running app in Android by BroadcastReceiver 如何在BroadcastReceiver中知道App是否在前台运行? - How to know in BroadcastReceiver if App is running on foreground? 如何从 BroadcastReceiver 中的 Workmanager 检查应用程序是否在前台? - How to check if app is on the foreground from Workmanager in BroadcastReceiver? 检查应用程序是在前台还是后台运行(使用同步适配器) - Check if app is running in foreground or background (with sync adapter) 如何检查Android应用程序是在后台运行还是在前台运行? - How to check if an Android application is running in the background or in foreground? 如何检查应用程序是在前台还是后台 - How to check whether the app is in foreground or background 如果应用程序正在运行,如何检查前台服务? - How to check in foreground service if the app is running? 检查应用程序是在前台还是后台 - Check if app's in foreground or background 如何从服务检查活动是否在后台/前台运行? - How to check if an activity is running in background/foreground from a service? 如何使用命令检查android服务是在后台还是前台运行? - How to check android service is running in background or foreground using command?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM