Why BroadcastReceiver works even when app is in background ?

后端 未结 9 905
感动是毒
感动是毒 2020-12-04 13:59

I am checking Internet connectivity in my app using BroadcastReceiver and I show an alert dialog if the connection is lost. It works fine. But my problem is that BroadcastRe

相关标签:
9条回答
  • 2020-12-04 14:15

    I better suggest you to check the internet setting from the application when someone opens it, here is the piece of code how i do it.

    public static boolean isNetworkConnected(Context ctx) {  
            ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);  
            NetworkInfo ni = cm.getActiveNetworkInfo();  
            if (ni == null) {  
                return false; // There are no active networks.  
            } else  
                return true;  
        }
    
    0 讨论(0)
  • 2020-12-04 14:16

    A simple way of finding whether the app is in foreground or not

    if((mContext.getPackageName().equalsIgnoreCase(
                    ((ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE))
                            .getRunningTasks(1).get(0).topActivity.getPackageName())))
    {
    //app is in foreground;
    }
    
    0 讨论(0)
  • 2020-12-04 14:30

    To make a Broadcast Receiver that fires only when you app is running follow the below code.

    1. Create your Broadcast Receiver like this:


    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    
    public class InternetStatusNotifier extends BroadcastReceiver{
    
        @Override
        public void onReceive(Context context, Intent intent) {
            //Recieve notification here
    
        }
    
    }
    

    2. Make an activity or fragment where you want the Broadcast Receiver to work like this:


    import android.app.Activity;
    import android.content.IntentFilter;
    import android.os.Bundle;
    
    public class MainActivity extends Activity {
        private InternetStatusNotifier mInternetStatusNotifier;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            mInternetStatusNotifier = new InternetStatusNotifier();
            super.onCreate(savedInstanceState);
        }
    
        @Override
        protected void onResume() {
            registerReceiver(mInternetStatusNotifier, new IntentFilter(
                    "android.net.conn.CONNECTIVITY_CHANGE"));
            super.onResume();
        }
    
        @Override
        protected void onPause() {
            unregisterReceiver(mInternetStatusNotifier);
            super.onPause();
        }
    

    Note: That is how you use broadcasts receiver in a screen specific manner. Only the screen displaying will receive broadcasts in this way. When you register broadcast using manifest file then they are even received when app is closed

    0 讨论(0)
提交回复
热议问题