Search code examples
androidandroid-intentbroadcastreceiverandroid-context

Using broadcastreceiver only on certain activity


I have two activities on is Register() and the other is ReadNews(). I am using broadcast receiver to detect internet connection automatically to execute some code.

 public void onReceive(Context context, Intent intent) {

    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
    Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
        if(MyApplication.isActivityVisible() == true) {
            Log.d("WifiReceiver", "Have Wifi Connection");
            Toast.makeText(context, "تم الإتصال بالشبكة", Toast.LENGTH_LONG).show();
            if (context instanceof RegisterActivity){
                Intent i = new Intent(context,
                        ReadNews.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }
            else {

            }
        }
    }

How can I start the ReadNews() activity only when the internet connection goes on while the user still using the RegisterActivity() only?
I tried to use the context like if (context instanceof RegisterActivity) but that doesn't seem right.


Solution

  • Thanks to @Squonk comment, I have followed that short comment instructions to accomplish what I want to do and now I want to share summary of my code to show how this thing works:
    Broadcast receiver inner class

     private BroadcastReceiver wifiReceiver =
            new BroadcastReceiver() {
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
        //do what ever you want here
    };
    

    registering Broadcast receiver in onResume()

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); //or any intent filter you want 
        registerReceiver(wifiReceiver, filter);
    }
    

    unregistering Broadcast receiver in onPause

     @Override
    protected void onPause() {
        super.onPause();        
        unregisterReceiver(wifiReceiver);
    }
    

    Important

    Don't use an <intent-filter> in the manifest. registering the broadcast receiver must be dynamic (onResume,onPause)