广播接收器和内存泄漏

时间:2016-02-11 02:55:28

标签: java android memory-leaks android-service android-broadcastreceiver

在我的应用中;我希望在我的所有服务中接收网络连接更改,因为我必须在本地和服务器上管理数据库。

我已经使BaseConnectivityService具有接收器以进行连接更改,如下所示:

public abstract class BaseConnectivityService extends IntentService {

    private ConnectivityManager mConnectivityManager;

    public BaseConnectivityService(String name) {
        super(name);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        registerReceivers();
    }

    @Override
    public void onDestroy() {
        unregisterReceivers();
        mConnectivityManager = null;
        super.onDestroy();
    }

    private void registerReceivers() {
        IntentFilter connectivityIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mConnectivityChangeReceiver, connectivityIntentFilter);
    }

    private void unregisterReceivers() {
        unregisterReceiver(mConnectivityChangeReceiver);
    }

    /**
     * will be invoked when network connectivity has been changed and network is in connected state
     */
    protected abstract void onNetworkConnected();

    /**
     * will be invoked when network connectivity has been changed and network is NOT in connected state
     */
    protected abstract void onNetworkDisconnected();

    /**
     * checks whether network is available and is in connected state
     *
     * @return true if network is connected; false otherwise
     */
    protected final boolean isNetworkConnected() {
        NetworkInfo activeNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isAvailable() && activeNetworkInfo.isConnected();
    }


    private final BroadcastReceiver mConnectivityChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (isNetworkConnected()) {
                onNetworkConnected();
            } else {
                onNetworkDisconnected();
            }
        }
    };
}

现在,如果我使用BaseConnectivityService扩展我的所有服务;是否会导致内存泄漏,因为系统会将服务保留在内存中以通知连接更改?

我看过this thread;这有点类似的问题。 正如Mark Murphy写的那样:

  

你会泄漏   内存,因为您的BroadcastReceiver会将组件保留在RAM中(甚至   如果它被销毁了)直到Android终止了   过程

它适用于我的场景吗?如果是,那么什么是避免内存泄漏并获得网络连接变化通知的好解决方案?

1 个答案:

答案 0 :(得分:1)

查看同一个帖子中的最后一个响应。您可以从Service类注册和取消注册广播接收器。如果与服务生命周期绑定,则不存在泄漏的可能性。