2 * Copyright (C) 2012 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.settings;
19 import android.content.BroadcastReceiver;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 import android.net.nsd.NsdManager;
24 import android.preference.Preference;
26 import android.preference.SwitchPreference;
29 * NsdEnabler is a helper to manage network service discovery on/off checkbox state.
31 public class NsdEnabler implements Preference.OnPreferenceChangeListener {
32 private final Context mContext;
33 private final SwitchPreference mSwitchPreference;
34 private final IntentFilter mIntentFilter;
35 private NsdManager mNsdManager;
37 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
39 public void onReceive(Context context, Intent intent) {
40 String action = intent.getAction();
41 if (NsdManager.ACTION_NSD_STATE_CHANGED.equals(action)) {
42 handleNsdStateChanged(intent.getIntExtra(NsdManager.EXTRA_NSD_STATE,
43 NsdManager.NSD_STATE_DISABLED));
48 public NsdEnabler(Context context, SwitchPreference pref) {
50 mSwitchPreference = pref;
51 mNsdManager = (NsdManager) mContext.getSystemService(Context.NSD_SERVICE);
52 mIntentFilter = new IntentFilter(NsdManager.ACTION_NSD_STATE_CHANGED);
55 public void resume() {
56 mContext.registerReceiver(mReceiver, mIntentFilter);
57 mSwitchPreference.setOnPreferenceChangeListener(this);
61 mContext.unregisterReceiver(mReceiver);
62 mSwitchPreference.setOnPreferenceChangeListener(null);
65 public boolean onPreferenceChange(Preference preference, Object value) {
67 final boolean desiredState = (Boolean) value;
68 mSwitchPreference.setEnabled(false);
69 mNsdManager.setEnabled(desiredState);
73 private void handleNsdStateChanged(int newState) {
75 case NsdManager.NSD_STATE_DISABLED:
76 mSwitchPreference.setChecked(false);
77 mSwitchPreference.setEnabled(true);
79 case NsdManager.NSD_STATE_ENABLED:
80 mSwitchPreference.setChecked(true);
81 mSwitchPreference.setEnabled(true);