1

私のコードは機能しましたが、突然機能しません。コードは次のとおりです。

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): Error! unhandled message{ 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 の解析の問題 ....」

何か考えはありますか?

4

1 に答える 1

2

ネットワークpermissionsが消えたり変更されたりしていないことを再確認してみてください。

android.permission.ACCESS_NETWORK_STATE
android.permission.ACCESS_WIFI_STATE
android.permission.INTERNET
android.permission.CHANGE_WIFI_MULTICAST_STATE
于 2012-09-05T16:55:37.383 に答える