在Eclipse中使用JmDNS进行服务发现:Wifistatemachine错误

时间:2012-04-23 22:17:12

标签: android eclipse jmdns

我的代码有效,但突然不起作用。代码如下。

public class AndroidDnssdDiscoveryTestActivity extends Activity {
/** Called when the activity is first created. */

android.net.wifi.WifiManager.MulticastLock lock;
android.os.Handler handler = new android.os.Handler();
final Context context = this;
AlertDialog alert=null;


public void onCreate(Bundle savedInstanceState) {

    /*
     * StrictMode.ThreadPolicy was introduced since API Level 9 and the default thread policy had been changed since API Level 11,
     * which in short, does not allow network operation (include HttpClient and HttpUrlConnection) get executed on UI thread. 
     * if you do this, you get NetworkOnMainThreadException. It needs to add the following 3 lines.
    */
     if (android.os.Build.VERSION.SDK_INT > 9) {
          StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
          StrictMode.setThreadPolicy(policy);
     }

     super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        handler.postDelayed(new Runnable() {
            public void run() {
                setUp();
            }
            }, 1000);
}

private String type = "_http._tcp.local.";
private JmDNS jmdns = null;
private String Servername ="test._http._tcp.local.";
private boolean _findSECE = false;
private ServiceListener listener = null;
private HttpClient httpclient = new DefaultHttpClient();
private ServiceInfo serviceInfo;

//private ServiceInfo serviceInfo;

private void setUp() {

    android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);

    lock = wifi.createMulticastLock("mylockthereturn");
    lock.setReferenceCounted(true);
    lock.acquire();

    try {
        jmdns = JmDNS.create();
        notifyUser("create");
        jmdns.addServiceListener(type, listener = new ServiceListener() {

            public void serviceResolved(ServiceEvent ev) {

                final String getName = ev.getInfo().getQualifiedName();
                final String getUrl = ev.getInfo().getURLs()[0];

                if(getName.equalsIgnoreCase(servername))
                {


                    Log.d("getName",getName);
                    Log.d("getUrl",getUrl);

                    // show alert
                    ((Activity) context).runOnUiThread(new Runnable() {

                        public void run() {
                            alertDialog(getName,getUrl);
                        }
                    });

                }else{


                        notifyUser("Name: " + getName+"\nURL: " + getUrl);
                        Log.d("getName",getName);
                        Log.d("getUrl",getUrl);


                }

            }

            public void serviceRemoved(ServiceEvent ev) {
                notifyUser("Service removed: " + ev.getName());
            }

            public void serviceAdded(ServiceEvent event) {
                // Required to force serviceResolved to be called again (after the first search)
                jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
            }
        });

        serviceInfo = ServiceInfo.create("_http._tcp.local.", "AndroidTest", 0, "plain test service from android");
        jmdns.registerService(serviceInfo);

    } catch (IOException e) {
        e.printStackTrace();
        return;
    }


}



public void alertDialog(final String getName, final String getUrl){
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage("SECE service found! Do you want to control the light?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {

                   Log.d("ACTION","BUTTON Pressed");
                   SendHttpPost(getName,getUrl);

               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    alert = builder.create();
    alert.show();

}

private void SendHttpPost(String getName, String getUrl){

    HttpGet httpget = new HttpGet(getUrl);

    try {
        HttpResponse response = httpclient.execute(httpget);
                    HttpEntity entity = response.getEntity();
        byte buffer[] = new byte[1024] ;
        InputStream is = entity.getContent() ;
        int numBytes = is.read(buffer) ;
        is.close();
        String entityContents = new String(buffer,0,numBytes) ;
        Log.d("getName",getName);
        Log.d("getUrl",getUrl);
        Log.d("replay",entityContents);

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private void notifyUser(final String msg) {
    handler.postDelayed(new Runnable() {

        public void run() {
            TextView t = (TextView)findViewById(R.id.text);
            t.setText("\n===========\n"+t.getText());
            t.setText(msg+t.getText());
        }
        }, 1);

}

@Override
    protected void onStart() {
    super.onStart();

}

@Override
    protected void onStop() {
    if (jmdns != null) {
        if (listener != null) {
            jmdns.removeServiceListener(type, listener);
            listener = null;
        }
        jmdns.unregisterAllServices();
        try {
            jmdns.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        jmdns = null;
    }
    lock.release();
    super.onStop();
}

}

我得到的错误如下 “ 04-23 21:56:25.031:E / WifiService(94):Multicaster binderDied 04-23 21:56:25.041:E / WifiStateMachine(94):错误!未处理的消息{what = 131156 when = -9ms} 04-23 21:56:34.562:E / WifiStateMachine(94):错误!未处理的消息{what = 131157 when = -3ms} 04-23 21:56:53.952:A / NetworkStats(94):读取网络统计数据的问题 04-23 21:56:53.952:A / NetworkStats(94):java.lang.IllegalStateException:解析idx 1的问题 .... “

你有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试仔细检查您的网络permissions尚未消失/更改。

android.permission.ACCESS_NETWORK_STATE
android.permission.ACCESS_WIFI_STATE
android.permission.INTERNET
android.permission.CHANGE_WIFI_MULTICAST_STATE