简体   繁体   中英

Memory leak - Service + thread

I would like to know if I am doing the right thing. I am clearly getting memory leaks, but I can not pin down where - I have submitted a simplified version of where I think the problem lies . . . is there a potential for leak in the following code?

public class MainActivity extends Activity {

    filterService mServer;

    private void startService() {
       Intent mIntent = new Intent(getApplicationContext(), filterService.class);
       startService(mIntent);
       bindService(mIntent, mConnection, BIND_AUTO_CREATE);
    }

    private void stopService() {
        stopService(new Intent(getApplicationContext(), filterService.class));
        unbindService(mConnection);
        mConnection = null;     
    }

    ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
            mServer = null;
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            LocalBinder mLocalBinder = (LocalBinder)service;
            mServer = mLocalBinder.getServerInstance();
        }
    };

    public void onDestroy() {
        super.onDestroy();
        stopService();
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService();
    }
}

Any comments would be most valuable - thank you.

Better unbind from your service in 'onStop()', because 'onDestroy()' may not be called.

If you use 'startService()' to make your service do whatever it is supposed to do and return with 'START_STICKY' from the 'onStartCommand()' method of the service, then it will not be destroyed.

See the documentation about bound services (The Basics):

When the last client unbinds from the service, the system destroys the service (unless the service was also started by startService()).

This way, you can keep your service alive even though the activity is stopped/ destroyed. As soon as it is finished, it can call 'stopSelf()'.

Another source for memory leaks could be a Handler used for communication with the bound service, but I can't judge that from your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM