简易浏览器App webview

时间:2023-11-10 16:37:44
简易浏览器App webview
简易浏览器App webview

使用
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView textView = new TextView(this);
        textView.setText("点击打开我的博客");
        textView.setGravity(Gravity.CENTER);
        setContentView(textView);
        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.cnblogs.com/baiqiantao/"));
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.putExtra(WebViewActivity.TITLE, "包青天的Android之旅");
                Toast.makeText(MainActivity.this, "Uri=" + intent.getData(), Toast.LENGTH_LONG).show();
                Log.i("bqt",
                        "TITLE=" + intent.getStringExtra(WebViewActivity.TITLE) + "Uri=" + intent.getData() + "\nScheme=" + intent.getScheme() + "\nType="
                                + intent.getType() + "\nFlags=" + intent.getFlags() + "\nPackage=" + intent.getPackage() + "\nAction=" + intent.getAction()
                                + "\nCategory=" + intent.getCategories());
                //TITLE=包青天的Android之旅
                //Uri=http://www.cnblogs.com/baiqiantao/
                //Scheme=http
                //Type=null
                //Flags=0
                //Package=null
                //Action=android.intent.action.VIEW
                //Category={android.intent.category.DEFAULT,//android.intent.category.BROWSABLE}
                startActivity(intent);
            }
        });
    }
}

代码-浏览器Activity
public class WebViewActivity extends Activity implements OnClickListener {
    public static final String TITLE = "标题";
    public static final String JS_INTERFACE = "Android";//JS调用类名
    private WebView webview;
    private ProgressBar progress_bar;
    private TextView tv_back;
    private TextView tv_title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_webview);
        initViews();
        initWebView();
    }
    private void initViews() {
        progress_bar = (ProgressBar) findViewById(R.id.progress_bar);
        webview = (WebView) findViewById(R.id.webview);
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_back.setOnClickListener(this);
        progress_bar.setIndeterminate(true);//自动在最小到最大值之间来回移动,不明确具体的值
        progress_bar.setVisibility(View.VISIBLE);
    }
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        webview.getSettings().setJavaScriptEnabled(true);//支持javascript。这个属性基本也是必须的,否则网页内容不会自适应手机屏幕
        webview.setWebViewClient(new MyWebViewClient(progress_bar));//在本WebView中显示网页内容。
        webview.addJavascriptInterface(new WebAppinterface(this), JS_INTERFACE);// 注册后可以在JS中调用此接口中定义的方法
        Intent intent = getIntent();
        if (intent != null) {
            String title = intent.getStringExtra(TITLE);
            if (!TextUtils.isEmpty(title)) tv_title.setText(title);
            String url = intent.getDataString();
            if (null != url && !"".equals(url)) {//防止空指针异常
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    if (url.startsWith("www.")) webview.loadUrl("http://" + url); //以"www."开头,添加"http://"前缀
                    else webview.loadUrl("http://www.baidu.com.cn/s?wd=" + url);//使用百度搜索
                } else webview.loadUrl(url);//以"http://"开头,直接加载页面
            } else Toast.makeText(this, "请先输入网址", 0).show();
        }
    }
    @Override
    //点击后退按钮不退出Activity,而是让WebView后退一页。也可以通过webview.setOnKeyListener设置
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
            webview.goBack(); //后退,goForward() 前进  
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            webview.loadUrl("about:blank");
            webview.destroy();
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.tv_back:
            finish();
            break;
        }
    }
}

代码-WebviewClint
public class MyWebViewClient extends WebViewClient {
    private ProgressBar mProgressBar;
    public MyWebViewClient(ProgressBar mProgressBar) {
        super();
        this.mProgressBar = mProgressBar;
    }
    @Override
    //打开网页时不调用系统浏览器, 而是在本WebView中显示
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        mProgressBar.setVisibility(View.VISIBLE);
        super.onPageStarted(view, url, favicon);
    }
    @Override
    public void onPageFinished(WebView view, String url) {
        mProgressBar.setVisibility(View.GONE);
        super.onPageFinished(view, url);
    }
}

代码-JS调用接口
/**
 * 在JS中可以调用此类中的方法
 */
public class WebAppinterface {
    private Activity mActivity;
    public WebAppinterface(Activity context) {
        this.mActivity = context;
    }
    public void recharge(int vipType) {
        Intent intent = new Intent(mActivity, Activity.class);
        Bundle mBundle = new Bundle();
        mBundle.putInt("item", vipType - 1);
        mActivity.startActivity(intent, mBundle);
    }
}

浏览器布局
<LinearLayout 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"
    android:orientation="vertical" >
    <RelativeLayout
        android:id="@+id/lk_activity_bar"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="#ffa726" >
        <TextView
            android:id="@+id/tv_back"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:clickable="true"
            android:drawableLeft="@drawable/left_selector"
            android:drawablePadding="5dp"
            android:gravity="center|left"
            android:paddingLeft="15dp"
            android:text="返回"
            android:textColor="#fff"
            android:textSize="14sp" />
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="活动详情"
            android:textColor="#fff"
            android:textSize="18sp" />
    </RelativeLayout>
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <ProgressBar
            android:id="@+id/progress_bar"
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:indeterminate="true"
            android:indeterminateDrawable="@drawable/progressbar_drawable"
            android:visibility="invisible" />
    </FrameLayout>
</LinearLayout>

清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bqt.browser"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="浏览器App"
        android:theme="@android:style/Theme.Holo" >
        <activity
            android:name=".MainActivity"
            android:label="主页面" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".WebViewActivity"
            android:label="包青天的浏览器" >
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:scheme="about" />
                <data android:scheme="javascript" />
            </intent-filter>
        </activity>
    </application>
</manifest>