Skip to content Skip to sidebar Skip to footer

Hit A Url Without Opening Browser In Android Studio

i have looked at many places, tried a ton of things but nothing to seem to work for me somehow. Can anyone please help me here. I have a simple url that i want to hit without openi

Solution 1:

You can call it as a web service and do nothing with the results. For example:

AsyncHttpClient client = newAsyncHttpClient();
client.get("http://172.17.27.173/yourpage", params, newAsyncHttpResponseHandler() {
    @OverridepublicvoidonSuccess(String response) { // 200 OK// Do nothing
    }
    @OverridepublicvoidonFailure(int statusCode, Throwable error, String content) { // Response not 200
    {
        // Some troubleshooting, etc.
    }
});

In order to see how to use the above code, you can take a look at here which has explained how to use the code for Android: http://loopj.com/android-async-http/

It is also possible to use some other library such as Apache Http client as well: https://hc.apache.org/

try {
        DefaultHttpClienthttpClient=newDefaultHttpClient();
        HttpPosthttpPost=newHttpPost(url);

        HttpResponsehttpResponse= httpClient.execute(httpPost);
        HttpEntityhttpEntity= httpResponse.getEntity();
        myContent = httpEntity.getContent();

    } catch ...

Solution 2:

Use this method to open url with in your application

You can call this url like your api calling, it calls url without any display. Or make an api(web service) and hit from the application and at api end call your url.

Solution 3:

First make a web view and then make it invisible so that it wont be displayed. Then use this web view to load the url the it will be ok and the external browser will not be executed.

val myWebView: WebView = findViewById(R.id.WebView)

use below line for the executing the url then it will be fine.

myWebView.loadUrl("http://192.168.100.3/on")
myWebView.loadUrl("http://192.168.100.3/off")

The demo program if we use toggle switch then it will be.

val myWebView: WebView = findViewById(R.id.WebView)

        val switch1: ToggleButton = findViewById(R.id.toggleButton)
        switch1.setOnCheckedChangeListener { _, isChecked ->
            Toast.makeText(this, if(isChecked) " ON"else" OFF", Toast.LENGTH_SHORT).show()

            if(isChecked){
               
                myWebView.loadUrl("http://192.168.100.3/on")

            }
            else{
               
                myWebView.loadUrl("http://192.168.100.3/off")

            }
}

Post a Comment for "Hit A Url Without Opening Browser In Android Studio"