Search code examples
javaandroidstatic-methodsandroid-context

How to pass context to a static method?


In my fragment i call a static method from another class

if (getActivity() != null) {
        Main.bindMusicService(getActivity().getApplicationContext(), position, songList);
}

Main class:

private static Context context;

private static ArrayList<Song> songList;

private static int songIndex;

public static void bindMusicService(Context c, int songPos, ArrayList<Song> songs){
    context = c;
    songIndex = songPos;
    songList = songs;
    /*mediaPlayerServiceIntent binds our connection to the MediaPlayerService. */
    if (!mServiceIsBound) {
        try {
            mediaPlayerServiceIntent = new Intent(c, MediaPlayerService.class);
            c.bindService(mediaPlayerServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        } catch (Exception e) {
            Log.e("Main", "Service is not bound!");
        }
    }else{
        Main.mediaPlayerService.startActionPlay(context, songList, songIndex);
    }
    Log.i("Main","Service is bound!");
}

I get this warning for the context

Do not place Android context classes in static fields; this is a memory leak

What is the right way to send my arraylist, adapter position and context to another method which is in another class?


Solution

  • Your problem is not sending the Context. Your problem is:

    private static Context context;
    

    If you are absolutely certain that you need something like that, replace it with:

    private static Application context;
    

    Adjust your method to take an Application as a parameter, and have your call to that method use getApplication() instead of getApplicationContext().

    IOW, your code is reasonably safe — you are using the Application context — but the details of your code is making Lint nervous.