Skip to content

Instantly share code, notes, and snippets.

@AfzalivE
Created August 27, 2014 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AfzalivE/82506de2e43961212dd6 to your computer and use it in GitHub Desktop.
Save AfzalivE/82506de2e43961212dd6 to your computer and use it in GitHub Desktop.
Memory leak
public class MyService extends Service implements OnSharedPreferenceChangeListener {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
public final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// do stuff
}
}
}
@AfzalivE
Copy link
Author

Fixed
public class MyService extends Service implements OnSharedPreferenceChangeListener {

    private Looper mServiceLooper;
    private ServiceHandler mServiceHandler;

    @Override
    public void onCreate() {

        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.  We also make it
        // background priority so CPU-intensive work will not disrupt our UI.
        HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    public static class ServiceHandler extends Handler {
       WeakReference<MyService> mServiceReference;
        public ServiceHandler(Looper looper, MyService myService) {
            super(looper);
            mServiceReference = new WeakReference(myService)<>;
        }

        @Override
        public void handleMessage(Message msg) {
            // do stuff
        }

    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment