Mann
Mann

Reputation: 606

How to get the activity which called the BroadcastReceiver?

I have a BroadcastReceiver which checks for NetworkChange, whether connected to Internet or not.

So in my application when the network is disconnected or connected, I want to know which activity has called the BroadcastReceiver, so that I can go back to previous activity after showing an alert informing about the network.

My code,

public class NetworkChangeReceiver extends BroadcastReceiver {

private android.widget.Toast Toast;

@Override
public void onReceive(final Context context, final Intent intent) {
    try {
        boolean isVisible = MyApplication.isActivityVisible();
        Context appContext = context.getApplicationContext();
        if (isVisible == true) {
            if (checkInternet(context)) {
                /*Intent i = new Intent(context, MainActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);*/


                Toast.makeText(context, "Network Available Do operations", Toast.LENGTH_LONG).show();
            } else {
                Intent i = new Intent(context, NoNetworkAlert.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
                Toast.makeText(context, "Network NOT Available Do operations", Toast.LENGTH_LONG).show();
            }

  .........
  ......

Here in the above code, when Internet is reconnected, if (checkInternet(context))I just want to get to the activity which triggered this.

Upvotes: 1

Views: 4949

Answers (3)

Sathish Kumar VG
Sathish Kumar VG

Reputation: 2172

I have a BroadcastReceiver which checks for NetworkChange, whether connected to Internet or not.

So in my application when the network is disconnected or connected, I want to know which activity has called the BroadcastReceiver, so that I can go back to previous activity after showing an alert informing about the network.

To get the current Activity in Broadcast receiver use the ActivityManager in Broadcast receiver to get the Activity without instance

ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
Log.i("ActivityManager ", "ActivityManager" + cn.toString());

To get Activity in the preferred Activity with instance better use Getter and Setter.

MyApplication.Java:

public class MyApplication extends Application {
   private Activity mCurrentActivity = null;
   // Gloabl declaration of variable to use in whole app
   public static boolean activityVisible; // Variable that will check the
                                 // current activity state
   public static boolean isActivityVisible() {
      return activityVisible; // return true or false
   }
   public static void activityResumed() {
      activityVisible = true;// this will set true when activity resumed
   }
   public static void activityPaused() {
      activityVisible = false;// this will set false when activity paused
   }
   public Activity getCurrentActivity(){
      return mCurrentActivity;
   }
   public void setCurrentActivity(Activity mCurrentActivity){
      this.mCurrentActivity = mCurrentActivity;
   }
}

MainActivity.Java:

public class MainActivity extends AppCompatActivity {
    private static TextView internetStatus;
    protected MyApplication mMyApp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMyApp = (MyApplication) this.getApplicationContext();
        internetStatus = (TextView) findViewById(R.id.internet_status);
        // At activity startup we manually check the internet status and change
        // the text status
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            changeTextStatus(true);
        } else {
            changeTextStatus(false);
        }
    }
    // Method to change the text status
    public void changeTextStatus(boolean isConnected) {
        // Change status according to boolean value
        if (isConnected) {
            internetStatus.setText("Internet Connected.");
            internetStatus.setTextColor(Color.parseColor("#00ff00"));
        } else {
            internetStatus.setText("Internet Disconnected.");
            internetStatus.setTextColor(Color.parseColor("#ff0000"));
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        MyApplication.activityPaused();// On Pause notify the Application
        clearReferences();
    }
    @Override
    protected void onResume() {
        super.onResume();
        MyApplication.activityResumed();// On Resume notify the Application
        mMyApp.setCurrentActivity(this);
    }
    protected void onDestroy() {
        clearReferences();
        super.onDestroy();
    }
    private void clearReferences() {
        Activity currActivity = mMyApp.getCurrentActivity();
        Log.e("Activity", "Activity" + currActivity);
        if (this.equals(currActivity))
            mMyApp.setCurrentActivity(null);
    }
}

InternetConnector_Receiver.Java:

public class InternetConnector_Receiver extends BroadcastReceiver {
    public InternetConnector_Receiver() {
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            boolean isVisible = MyApplication.isActivityVisible();
            Log.i("Activity is Visible ", "Is activity visible : " + isVisible);
            ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
           Log.i("ActivityManager", "Activity Name:" + cn.toString());
            // If it is visible then trigger the task else do nothing
            if (isVisible == true) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager
                        .getActiveNetworkInfo();
                // Check internet connection and accrding to state change the
                // text of activity by calling method
                if (networkInfo != null && networkInfo.isConnected()) {
                    new MainActivity().changeTextStatus(true);
                } else {
                    new MainActivity().changeTextStatus(false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Manifest Permission:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


<application
    android:name="com.internetconnection_demo.MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!-- Broadcast receiver declaration in manifest file and make sure to enable it -->
    <receiver
        android:name="com.internetconnection_demo.InternetConnector_Receiver"
        android:enabled="true" >
        <intent-filter>
            <!-- Intent filters for broadcast receiver -->
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            <action android:name="android.net.wifi.STATE_CHANGE" />
        </intent-filter>
    </receiver>
</application>

Upvotes: 0

AbhayBohra
AbhayBohra

Reputation: 2117

Do something like this in your activity

BroadcastReceiver br=new NetworkChangeReceiver ();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(br, filter);

And in your menifest

<receiver
            android:name=".NetworkChangeReceiver "
            android:exported="true">
            <intent-filter>

                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>

Upvotes: 0

Bijesh
Bijesh

Reputation: 357

I assume the current activity on the top is the one which triggers the NetworkChangeListener. If so you can use below code snippet,

ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;

which will give the current Activity on the top.

Upvotes: 1

Related Questions