0
最近我一直在玩Android的網絡服務發現功能。我有一切工作,但由於某種原因,我不能讓NsdManager.RegistrationListener
現在被調用。Android網絡服務發現不解僱聽衆
我用一個簡單的回調初始化它,然後調用registerService
,但它不叫onServiceRegistered
或onRegistrationFailed
。代碼如下。如果有問題,我正在服務中執行此註冊。
我在日誌中看到的是「註冊服務」,但從來沒有一個在監聽器中的回調。
private NsdManager mNsdManager;
private NsdManager.RegistrationListener mRegistrationListener;
@Override
public void onCreate() {
super.onCreate();
mNsdManager = (NsdManager) getApplicationContext().getSystemService(getApplicationContext().NSD_SERVICE);
initializeRegistrationListener();
startAdvertising();
}
public void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
@Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.i("myapp", "failed");
}
@Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
}
@Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
Log.i("myapp", "success");
}
@Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
}
};
}
public void startAdvertising() {
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setPort(new ServerSocket(0).getLocalPort());
serviceInfo.setServiceName("_myapp_one");
serviceInfo.setServiceType("_http._tcp.");
Log.i("myapp", "registering service");
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}