package edu.princeton.bitcointwofactorauth.android; /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context; import android.net.nsd.NsdServiceInfo; import android.net.nsd.NsdManager; import android.util.Log; public class NsdHelper { MainActivity mContext; NsdManager mNsdManager; NsdManager.ResolveListener mResolveListener; NsdManager.DiscoveryListener mDiscoveryListener; NsdManager.RegistrationListener mRegistrationListener; public static final String SERVICE_TYPE = "_bitcointwofactor._tcp."; public static final String TAG = "NsdHelper"; public String mServiceName = "BitcoinTwoFactor"; NsdServiceInfo mService; public NsdHelper(MainActivity context) { mContext = context; mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE); } public void initializeNsd() { initializeDiscoveryListener(); } public void initializeDiscoveryListener() { mDiscoveryListener = new NsdManager.DiscoveryListener() { public void onDiscoveryStarted(String regType) { Log.d(TAG, "Service discovery started"); } public void onServiceFound(NsdServiceInfo service) { Log.d(TAG, "Service discovery success" + service); if (!service.getServiceType().equals(SERVICE_TYPE)) { Log.d(TAG, "Unknown Service Type: " + service.getServiceType()); } else if (service.getServiceName().equals(mServiceName)) { Log.d(TAG, "Same machine: " + mServiceName); } else { Log.d(TAG, "Trying to resolve " + service); mNsdManager.resolveService(service, mContext); } } public void onServiceLost(NsdServiceInfo service) { Log.e(TAG, "service lost" + service); if (mService == service) { mService = null; } } public void onDiscoveryStopped(String serviceType) { Log.i(TAG, "Discovery stopped: " + serviceType); } public void onStartDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery failed: Error code:" + errorCode); mNsdManager.stopServiceDiscovery(this); } public void onStopDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery failed: Error code:" + errorCode); mNsdManager.stopServiceDiscovery(this); } }; } public void discoverServices() { mNsdManager.discoverServices( SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener); } public void stopDiscovery() { mNsdManager.stopServiceDiscovery(mDiscoveryListener); } public NsdServiceInfo getChosenServiceInfo() { return mService; } public void tearDown() { stopDiscovery(); } }