Wednesday, June 26, 2013

Web browser by Action View

Today I am going to share the code for open web browser by action view in android.
In this article we will create an application which will open a user input website in a web browser. In order to open a web browser, we will create an intent object with ACTION_VIEW as action and data with “http” in the url. Since http request is invoked by the external browser, no explicit permission is needed for this application.

activity_main.xml

?
1
2
3
4
5
6
<linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
  
    <edittext android:hint="@string/hnt_te_url" android:id="@+id/te_url" android:inputtype="text" android:layout_height="wrap_content" android:layout_width="fill_parent">
  
    <button android:id="@+id/btn_browse" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="@string/lbl_btn_browse">
</button></edittext></linearlayout>

MainActivity.java


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.sunil.browserview;
 
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
 
public class MainActivity extends Activity implements OnClickListener{
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
         
        Button btn = (Button) findViewById(R.id.btn_browse);
        btn.setOnClickListener(this);
    }
            @Override
            public void onClick(View v) {
                EditText txt = (EditText) findViewById(R.id.te_url);
         
                Intent intent = new Intent("android.intent.action.VIEW");
             
                Uri data = Uri.parse("http://"+txt.getText().toString());
             
                intent.setData(data);
         
                startActivity(intent);
             
    }
}
   

No comments:

Post a Comment