1

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

我已经制作了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;是否会导致内存泄漏,因为该系统会将服务保留在内存中以通知连接更改?

我读过这个线程;这有点类似的问题。正如马克墨菲在那里写的那样:

您将泄漏内存,因为您的 BroadcastReceiver 会将组件保留在 RAM 中(即使它已被销毁),直到 Android 终止进程。

Is it be applicable for my scenario? If yes, what can be the good solution for avoiding memory leak and getting notified of network connectivity changes?

4

1 回答 1

1

Look at the last response in the same thread. You can register and unregister broadcast receiver from Service class. There is no chance for leak in case if it is binded with Service life cycle.

于 2016-02-11T03:24:11.500 回答