Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Several activities sharing common code

Tags:

java

android

I have an Android application composed by several Activities. Most of them need to check whether an active network is available or not:

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    ...
}

I would like to move that code to a helper class in order to avoid the need to write that code in every Activity, but calls to getSystemService are only allowed from an Activity.

The other alternative is to move that code to a parent activity use inheritance but:

  1. Every activity already extends from android.app.Activity
  2. Some of my activities already extend from a common my.package.BaseActivity (Activity <- BaseActivity <- XXXActivity)

so I don't like this idea very much.

What do you recommend in this case? Is there any other alternative?

like image 616
Guido Avatar asked Sep 14 '26 17:09

Guido


1 Answers

Well, you could still create a helper class and pass a reference of the activity to it.

public boolean isNetworkAvailable(Context c) {
    ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
    ...
}

getSystemService is a public method, so it should work outside of the Activity scope.

You could pass it by calling it like this:

helperClassObj.isNetworkAvailable(YourActivity.this);

Hope this works for you.

like image 160
xil3 Avatar answered Sep 16 '26 08:09

xil3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!