Android广播接收器:RegisterService

时间:2016-11-04 11:57:13

标签: android broadcastreceiver

我已经构建了一个应用程序来更改设备上连接的wifi网络。我需要在wifi连接时注册服务,并在用户更改活动后或者在指定时间之后理想地取消注册。 我已尝试按如下方式扩展BroadcastReciever类,但这不会取消注册该服务并创建它的多个实例。

public class ConnectionListener extends BroadcastReceiver {

    private static final String TAG = "ConnectionListener";
    private BroadcastService accessPlayerService;
    private boolean isRegistered = false;

    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnected();

        if (isConnected) {
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {

                accessPlayerService = new BroadcastService(context, "Welcome-Service");
                Log.i(TAG, "onReceive: Registering Service");
                if (!isRegistered){
                    accessPlayerService.registerService();
                    isRegistered = true;
                }

            } else {
                if (isRegistered) {
                    isRegistered = false;
                    accessPlayerService.unregisterService();
                }
            }
        }
    }
}

我还尝试在活动的onResume()onPause()中注册和取消注册,但是当网络发生变化或者在这两种方法之间或之间不可用时,它仍然可以解决问题。

0 个答案:

没有答案