【问题标题】:Android button to call www addressAndroid按钮调用www地址
【发布时间】:2018-11-17 16:07:52
【问题描述】:

我需要制作一个带有按钮的简单应用程序,它将调用一些 URL。我在我的 Rpi 上有一个 apache 服务器,我用它来通过发送这样的 GET URL 来控制 GPIO

http://192.168.0.105/index.php?pin=2&status=0

在 android studio 中我只做了一个 onclick 按钮。

问题是我不熟悉 java 和 android,所以这是我的问题 - 让这个按钮发送 URL 的最简单方法是什么?我找到了一些关于从服务器发送或接收数据的教程,但这不是我想做的。

【问题讨论】:

  • 我希望您知道这样一个事实,即您的 IP 地址只能从您的本地网络访问。

标签: java android android-studio raspberry-pi


【解决方案1】:
  1. 为清单添加权限:<uses-permission android:name="android.permission.INTERNET" />

  2. 创建一个类:

    class RequestTask extends AsyncTask<String, String, String> {
        String response;
        ProgressDialog dialog;
    
        @Override
        protected String doInBackground(String... params) {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(params[0]); // or HttpPost if you need
    
                ResponseHandler<String> resHandler = new BasicResponseHandler();
                response = httpClient.execute(httpGet, resHandler);
           } catch (Exception e) {
               System.out.println("E: " + e);
           }
    
           return null;
        }
    
        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            dialog.show();
            super.onPreExecute();
        }
    
        @Override
        protected void onPostExecute(String result) {
            dialog.dismiss();
            super.onPostExecute(result);
        }
    }
    
  3. 来电使用:new RequestTask().execute("http://192.168.0.105/index.php?pin=2&amp;status=0")

【讨论】:

  • 感谢您的精彩回复!但是我遇到了一些错误,知道我缺少哪些库吗? photo
  • @SlippinJimmy 我更新了答案,这个类需要插入MainActivity.java。此处描述了导入的自动放置:stackoverflow.com/a/16616085/9200394
  • 谢谢,我还需要实现 'org.apache.httpcomponents:httpcore:4.4.5' 和 'org.apache.httpcomponents:httpclient:4.5'。但我仍然遇到另一个错误photo
  • @SlippinJimmy 在此处粘贴您的代码,我将进行所有必要的更正:codeshare.io/5oX99r
  • 我把我的代码粘贴到了你给我的那个链接里。现在我得到了一些其他错误photo
【解决方案2】:

您可以在单击事件的按钮内使用此代码。点击后打开网址。

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("<your URL>"));
startActivity(browserIntent);

此外,如果您想作为 Web 客户端连接,但不想在浏览器中打开 - 您可以使用:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.someplace.com");

ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);

【讨论】:

  • 另外添加一个事实,即您需要向清单 (&lt;uses-permission android:name="android.permission.INTERNET" /&gt;) 添加权限,并且您不能在 UI 线程中使用网络。代码必须在另一个线程中运行或将其包装在 AsyncTask 中
【解决方案3】:

最简单的方法是使用 volley 库。

在清单中声明应用程序标签之外的互联网权限:&lt;uses-permission android:name="android.permission.INTERNET" /&gt;

在 build.gradle 文件的依赖项中添加这一行:implementation 'com.android.volley:volley:1.0.0'

创建一个名为 VolleySingleton 的 java 文件并从 file in github 复制文件内容,只是不要复制包名。

在按钮内点击添加这些行:

url = "http://192.168.0.105/index.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
            //Do what ever you need to do with the response here.
            //If you don't need to return any response just echo OK from the php so that you become sure that the thing is working fine.
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
             Log.d("Error.Response", response);
       }
    }
) {     
    @Override
    protected Map<String, String> getParams() 
    {  
            Map<String, String>  params = new HashMap<String, String>();  
            params.put("pin", "2");  
            params.put("status", "0");

            return params;  
    }
};

VolleySingleton.getmInstance(getApplicationContext()).addToRequestQue(postRequest);

【讨论】:

  • 非常感谢重播!我的 MainActivity 是否需要一些额外的实现来运行它? photo
【解决方案4】:

我已经创建了类似的功能

看看对你有没有帮助

您需要获得使用 Internet 的权限。在清单文件中,在应用程序标签之外声明互联网权限: &lt;uses-permission android:name="android.permission.INTERNET" /&gt;

创建一个活动(WebViewActivity.java)

public class WebViewActivity extends AppCompatActivity {

private static final String TAG = "WebViewActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web_view);

    Log.d(TAG, "onCreate: Started");

    Bundle extras = getIntent().getExtras();
    assert extras != null;
    String pin = extras.getString("pin"); //you can use getInt("pin") also, but afterwards in the url, it will be converted to String back, so it is not needed
    String status = extras.getString("status"); //you can use getInt("status") also, but afterwards in the url, it will be converted to String back, so it is not needed

    WebView webView = new WebView(this);
    setContentView(webView);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true); //This is required to enable javascript that is required by some pages
    String url = "http://192.168.0.105/index.php?pin" + pin + "&status=" + status;

    webView.loadUrl(url);

    Log.d(TAG, "url accessed: " + url);

    finish();//If you need to see the output after accessing the http page, then remove this line. Otherwise just copy as it is 
}

}

在MainActivity中,启动上面创建的activity即可。

public class MainActivity extends AppCompatActivity{
    int pin = 0, status = 2;// You can modify the values according to your requirements
    //....
    //....
    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getApplicationContext(), WebViewActivity.class);
                    intent.putExtra("pin", pin);
                    intent.putExtra("status", status);
                    startActivity(intent);
                    Toast.makeText(MainActivity.this, "URL Opened and pin, status values are successfully updated", Toast.LENGTH_SHORT).show();

                }
            });
    //....
    //....
}

如果您想知道在 xml 文件中放入什么 (activity_web_view.xml) 保持原样,我使用下面的代码发送值,就像你试图发送一样。

activity_web_view.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WebViewActivity" />

【讨论】:

    猜你喜欢
    • 2013-11-03
    • 2012-05-26
    • 2022-01-24
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多