HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Base activity for handling network state changes in Android

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
handlingandroidchangesforstateactivitynetworkbase

Problem

I had the need in one of my activies to handle displaying a message to the user when the network disconnected, and then reload the data for a RecyclerView adapter when the network reconnected to ensure it was up to date.

After getting that working for my use case, I wanted to make the implementation more abstract for reuse in other, future activities.

While this works as expected, I'm still relatively new to Android development. Is there any better/recommended way of doing this, or any areas of my solution that might be improved?

Here is my current implementation:

```
/**
* Base activity that provides methods to handle network connect and disconnect events, and to
* optionally display an error message Snackbar to the user on network disconnect.
*/
public abstract class NetworkAwareActivity extends AppCompatActivity {
private Snackbar networkErrorSnackbar;
private String errorMessageString;
private boolean errorMessageEnabled = false;
private boolean errorMessageDismissible = false;
private View errorMessageParentView;

/**
* Called when the network becomes connected from a disconnected state.
*/
protected abstract void onNetworkConnected();

/**
* Called when the network becomes disconnected from a connected state.
*/
protected abstract void onNetworkDisconnected();

/**
* This method should be called once in onCreate() to setup the error Snackbar.
* After this has been called, the error Snackbar will remain enabled for the life of this Activity.
* Not calling this method will only prevent the Snackbar from being displayed;
* the onNetworkConnected() and onNetworkDisconnected() methods will still work as expected.
* Subsequent calls to this method are ignored.
* @param message Message to display in Snackbar
* @param dismissible Whether the Snackbar should be dismissible
*/
public void enableErrorMessageSnackbar(String message, boolean dismissible) {

Solution

The only problem I'm foreseeing is that, you can't implement this solution in Fragment or View, and thus you'll have pass the action from particular Activity to its Fragment or View. I would just create a similar kind of design without an Activity in some kind of singleton where it would maintain a list of listeners who are listening to this network changes!

You can then add/remove listeners from Activity/Fragment or even a View, and thus you are not restricted to having just child activity implementation.

Context

StackExchange Code Review Q#140501, answer score: 2

Revisions (0)

No revisions yet.