2014-11-23 110 views
-1

首先,我对Java很新,我正在尝试为家庭自动化制作应用程序。 在服务器端,我有一个PHP脚本,将切换我的灯,现在我想发送一个Get请求与Android运行PHP脚本,因为PHP是服务器端。 现在,当我按下按钮时,应用程序“正好”崩溃,日志中没有任何内容。http获取android应用程序崩溃没有结果,也没有错误

这是我对按钮的代码:

Button bA = (Button) findViewById(R.id.button); 
    bA.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      try { 
       HttpClient httpclient = new DefaultHttpClient(); 

       HttpGet request = new HttpGet(); 
       URI Aswitch = new URI("http://192.168.1.186/a-switch.php"); 
       request.setURI(Aswitch); 
       HttpResponse response = httpclient.execute(request); 

      } catch (ClientProtocolException e){ 
       Log.e("log_tag", "ClientProtocol error"); 
      } catch(IOException e){ 
       Log.e("log_tag", "IO error"); 
      } catch(URISyntaxException e) { 
       Log.e("log_tag", "URISytax error"); 
      } 


     } 
    }); 
+2

检查logcat的。最有可能它是一个[NetworkOnMainThreadException](http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html) – 2014-11-23 16:33:20

+0

张贴您的logcat?我们无法预测您的错误。 – stacktry 2014-11-23 17:07:55

回答

2

试试这个:

Button bA = (Button) findViewById(R.id.button); 
    bA.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 


      new Thread(new Runnable() { 

       public void run() { 
        try { 
         HttpClient httpclient = new DefaultHttpClient(); 

         HttpGet request = new HttpGet(); 
         URI Aswitch = new URI("http://192.168.1.186/a-switch.php"); 
         request.setURI(Aswitch); 
         HttpResponse response = httpclient.execute(request); 

        } catch (ClientProtocolException e){ 
         Log.e("log_tag", "ClientProtocol error"); 
        } catch(IOException e){ 
         Log.e("log_tag", "IO error"); 
        } catch(URISyntaxException e) { 
         Log.e("log_tag", "URISytax error"); 
        } 

       } 
      }).start(); 


     } 
    }); 
+0

非常感谢,它似乎工作 – user2302718 2014-11-23 17:24:28

+0

快乐编码:) – 2014-11-23 17:26:20

+0

BTW..You可以标记我的答案,并把它投票;) – 2014-11-23 17:28:39

0

也许你正在主线程对这个请求。使用AsyncTask来完成您的联网请求。 也不要忘了许可android.permission.INTERNET添加到清单文件

相关问题