mattfred
mattfred

Reputation: 2759

Android service class variables

I have built a singleton utility class that holds a couple of android service variables. I did this to try to avoid needing to pass in a 'Context' reference each time I use a method in the class. Will keeping a reference to a service cause any problems?

public class ConnectivityUtil {

    // TODO: 5/24/2017 Is keeping a service as a member variable a good ida?
    private static ConnectivityUtil instance;
    private final ConnectivityManager connectivityManager;
    private final WifiManager wifiManager;

    private ConnectivityUtil(Context context) {
        connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        wifiManager = (WifiManager) context.getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
    }

    public static void init(Context context) {
        instance = new ConnectivityUtil(context);
    }

    public static ConnectivityUtil getInstance() {
        return instance;
    }

    ...
}

Upvotes: 0

Views: 359

Answers (1)

Andrey Danilov
Andrey Danilov

Reputation: 6602

It depends on what type of Context do you pass.

If you pass Application Context it is good practice:

inside service:

ConnectivityUtil.init(MyService.this.getApplicationContext());

If you pass Service directly

ConnectivityUtil.init(MyService.this);

You will get memory leak after service will be destroyed.

But best practice is init your singleton classes in Application class:

public class MainApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        ConnectivityUtil.init( getApplicationContext());
    }
}

So your Singleton will be created with application. Result is the same.

Upvotes: 1

Related Questions