2016-03-16 51 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

相關問題