Remote service, leaks activity when rotating

自古美人都是妖i 提交于 2019-12-04 07:42:30
finlir

Because there are two processes there are also two garbage collectors involved.

The service and client garbage collector. The service handles small IBinder objects (IRemoteListener) which are not so important to garbage collect fast. From the client side these IBinder objects holds a reference to an activity which is big.

The activity can't be garbage collected until the service have garbage collected the IBinder objects so it will be leaked until that happens. The solution is to change the listener into a static inner class. If you want to access something in the activity you have to use a weak reference.

Here's a related question and an explanation by Dianne Hackborn; https://stackoverflow.com/a/12206516/1035854

Some code:

private static class MyRemoteListener extends IRemoteListener.Stub {
    private final WeakReference<Activity> mWeakActivity;

    public MyRemoteListener(Activity activity) {
        mWeakActivity = new WeakReference<Activity>(activity);
    }

    @Override
    public void onMessage(String text) throws RemoteException {
        Activity activity = mWeakActivity.get();
        if (activity != null) {
            // ((MainActivity)activity).handleOnMessage(text);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!