1 /* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17 package com.android.settings; 18 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.CheckBoxPreference; 25 import android.preference.Preference; 26 import android.preference.PreferenceScreen; 27 28 import com.android.settings.R; 29 30 /** 31 * NsdEnabler is a helper to manage network service discovery on/off checkbox state. 32 */ 33 public class NsdEnabler implements Preference.OnPreferenceChangeListener { 34 private final Context mContext; 35 private final CheckBoxPreference mCheckbox; 36 private final IntentFilter mIntentFilter; 37 private NsdManager mNsdManager; 38 39 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 40 @Override 41 public void onReceive(Context context, Intent intent) { 42 String action = intent.getAction(); 43 if (NsdManager.ACTION_NSD_STATE_CHANGED.equals(action)) { 44 handleNsdStateChanged(intent.getIntExtra(NsdManager.EXTRA_NSD_STATE, 45 NsdManager.NSD_STATE_DISABLED)); 46 } 47 } 48 }; 49 50 public NsdEnabler(Context context, CheckBoxPreference checkBoxPreference) { 51 mContext = context; 52 mCheckbox = checkBoxPreference; 53 mNsdManager = (NsdManager) mContext.getSystemService(Context.NSD_SERVICE); 54 mIntentFilter = new IntentFilter(NsdManager.ACTION_NSD_STATE_CHANGED); 55 } 56 57 public void resume() { 58 mContext.registerReceiver(mReceiver, mIntentFilter); 59 mCheckbox.setOnPreferenceChangeListener(this); 60 } 61 62 public void pause() { 63 mContext.unregisterReceiver(mReceiver); 64 mCheckbox.setOnPreferenceChangeListener(null); 65 } 66 67 public boolean onPreferenceChange(Preference preference, Object value) { 68 69 final boolean desiredState = (Boolean) value; 70 mCheckbox.setEnabled(false); 71 mNsdManager.setEnabled(desiredState); 72 return false; 73 } 74 75 private void handleNsdStateChanged(int newState) { 76 switch (newState) { 77 case NsdManager.NSD_STATE_DISABLED: 78 mCheckbox.setChecked(false); 79 mCheckbox.setEnabled(true); 80 break; 81 case NsdManager.NSD_STATE_ENABLED: 82 mCheckbox.setChecked(true); 83 mCheckbox.setEnabled(true); 84 break; 85 } 86 } 87 } 88