2016-03-16 50 views
1

我想使用调用Arduino设备上的URL来打开和关闭灯光的按钮来制作简单的Android应用程序。打开网页浏览器并不是必须的。Java Android - 在没有打开浏览器的情况下按下按钮时调用URL

我对Android相当陌生,我已经在这里搜索并找到了一些建议,但它们并不适合我。

也许有人可以让我在正确的方向吗?

这是我的代码到目前为止,当我按下按钮时,没有任何反应。

package de.triscus.arduinoweb; 


import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.view.View.OnClickListener; 


import java.io.IOException; 

import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 


public class HomeLight extends AppCompatActivity implements OnClickListener { 
    String msg = "Android : "; 
    private Button lichterkette1; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_home_light); 

     lichterkette1 = (Button) findViewById(R.id.Lichterkette1); 
     lichterkette1.setOnClickListener(this); 
    } 

    public void onClick(View v) { 
     URL url = null; 
     HttpURLConnection urlConnection = null; 
     switch (v.getId()) 

     { 
      case R.id.Lichterkette1: 

       try { 

        url = new URL("http://192.168.2.106/?Lichterkette=1"); 
        urlConnection = (HttpURLConnection) url.openConnection(); 
        // urlConnection = (HttpURLConnection) url.openConnection(); 
        Log.d(msg, "Lichterkette1 pressed"); 
        //InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
        // Log.d(msg, InputStream); 

       } catch (MalformedURLException e) { 
        e.printStackTrace(); 
        Log.d(msg, "URL Malformed"); 
       } catch (IOException e) { 
        e.printStackTrace(); 
        Log.d(msg, "IO exception"); 
       } finally { 
        urlConnection.disconnect(); 
        Log.d(msg, "Disconnected"); 
       } 

     } 


    } 


} 

这里是logcat的输出:

03-16 15:19:26.133 9805-9805/? I/art: Late-enabling -Xcheck:jni 
03-16 15:19:26.143 9805-9805/? I/art: VMHOOK: rlim_cur : 0 pid:9805 
03-16 15:19:26.173 9805-9815/? I/art: Debugger is no longer active 
03-16 15:19:26.193 9805-9805/? E/Typeface: SANS_LOC file not found. 
03-16 15:19:26.584 9805-9805/? D/Atlas: Validating map... 
03-16 15:19:26.684 9805-9835/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.AF.1.1_RB1.05.00.02.006.020 - CR771817() 
              OpenGL ES Shader Compiler Version: E031.25.03.06 
              Build Date: 03/04/15 Wed 
              Local Branch: 
              Remote Branch: refs/tags/AU_LINUX_ANDROID_LA.AF.1.1_RB1.05.00.02.006.020 
              Local Patches: NONE 
              Reconstruct Branch: NOTHING 
03-16 15:19:33.481 9805-9805/de.triscus.arduinoweb D/Android :: Lichterkette1 pressed 
03-16 15:19:33.481 9805-9805/de.triscus.arduinoweb D/Android :: Disconnected 
03-16 15:19:34.832 9805-9805/de.triscus.arduinoweb D/Android :: Lichterkette1 pressed 
03-16 15:19:34.832 9805-9805/de.triscus.arduinoweb D/Android :: Disconnected 

预先感谢您

Triscus

PS:互联网/网络的使用是允许

+0

这是行得通的。您的输出表示您正在连接按钮按下的部分,然后最终在您完成时断开连接。 – zgc7009

回答

1

网络oprations /调用不能做主线程。你需要从另一个线程或异步任务或意图服务

注运行:所有的UI调度研究768,16完成onPostExecute,onPreExecute

下面的代码可以帮助你解决。

public void onClick(View v) { 
switch (v.getId()) 
{ 
    new Lichterkette().execute(); 
} 
} 


    class Lichterkette extends AsyncTask<String,Void,String>{ 
      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
      } 

      @Override 
      protected String doInBackground(String... params) { 
       StringBuilder sb=null; 
       BufferedReader reader=null; 
       String serverResponse=null; 
       try { 

        URL url = new URL("http://192.168.2.106/?Lichterkette=1"); 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        connection.setConnectTimeout(5000); 
        connection.setRequestMethod("GET"); 
        connection.connect(); 
        int statusCode = connection.getResponseCode(); 
        //Log.e("statusCode", "" + statusCode); 
        if (statusCode == 200) { 
         sb = new StringBuilder(); 
         reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
         String line; 
         while ((line = reader.readLine()) != null) { 
          sb.append(line + "\n"); 
         } 
        } 

        connection.disconnect(); 
        if (sb!=null) 
         serverResponse=sb.toString(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } finally { 
        if (reader != null) { 
         try { 
          reader.close(); 
         } catch (Exception e) { 
          e.printStackTrace(); 
         } 
        } 
       } 
       return serverResponse; 
      } 

      @Override 
      protected void onPostExecute(String s) { 
       super.onPostExecute(s); 
       //All your UI operation can be performed here 
       System.out.println(s); 
      } 
     } 
+0

将case语句移入switch语句后,这起作用。谢谢,现在我不必坐在黑暗中:) – Triscus

+0

很高兴帮助你....雅应该被移到外面的开关我编辑了我的答案。如果它为你工作可以接受我的答案。 –

0

我要尽可能地回答这个问题,希望它不仅能帮助你,还能帮助你thers。您寻找的类称为HttpPost或HttpGet。尽管您正在使用的URLConnection也应该起作用。 HttpPost和HttpGet是而不是ASYNC所以你可能需要从另一个线程或意向服务运行它。

您可以发送POST请求,如以下

HttpPost post = new HttpPost(String.format(<Your URL goes here>)); 

try { 
    //Set the header for the http post 
    post.setHeader("Content-type", "application/x-www-form-urlencoded"); 

    //Set the contents of the http post (JSON FORMAT) 
    post.setEntity(new StringEntity(<JSON STRING>)); 

    //Send the post and get the response back 
    HttpClient client = this.createHttpClient(); 
    HttpResponse response = client.execute(post); 
    //process your response here 

} catch (Exception e) { 
    Log.e(TAG, "Error", e); 
} 

的Http获取大致遵循相同的格式。

这是一种非常快速直接的方式,可以在不使用浏览器的情况下发出获取和发布请求。唯一的问题是,他们是而不是异步,就像我之前提到的,但它是非常重要的。他们与任何其他api一起工作。所以唯一的问题是你需要确保你的Arduino的行为像一个合适的网络服务器。

+0

我必须导入哪些模块才能使用HttpGet和HttpPost? – Triscus

相关问题