Java Android - 在不打开浏览器的情况下按下按钮时调用URL

时间:2016-03-16 14:35:14

标签: java android url arduino

我想创建一个简单的Android应用程序,其中的按钮可调用Arduino设备上的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

P.S。:允许使用互联网/网络

2 个答案:

答案 0 :(得分:3)

网络操作/调用无法完成主线程。您需要从另一个线程或异步任务或目标服务

运行它

注意:所有UI操作都应该在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);
            }
        }

答案 1 :(得分:0)

我将尽可能地回答这个问题,希望它不仅有助于你,还有助于其他人。您要查找的类称为HttpPost或HttpGet。虽然你正在使用的URLConnection也应该工作。 HttpPost和HttpGet 不是ASYNC 所以你可能需要从另一个线程或意图服务运行它。

您可以发送以下

之类的帖子请求
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获取大致相同的格式。

这是一种非常直接的方式,可以在不使用浏览器的情况下发送get和post请求。唯一的问题是,他们不是异步,就像我之前提到的那样,但它非常重要。他们与任何休息api一起工作。所以唯一的问题是你需要确保你的Arduino表现得像一个合适的网络服务器。