webview跳转加载数据

本文介绍了一款基于Android平台的网络新闻应用开发过程,包括如何使用WebView加载新闻内容、实现网络数据请求、判断网络状态等功能,并提供了完整的代码示例。
                <----布局---->
                <?xml version="1.0" encoding="utf-8"?>
                <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <WebView
                        android:id="@+id/web_view"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                    </WebView>

                </LinearLayout>


            <-----webview的主页面----->

            package com.example.a02_httpurlconnnection_newstop_03;

            import android.app.Activity;
            import android.content.Intent;
            import android.os.Bundle;
            import android.webkit.WebSettings;
            import android.webkit.WebView;
            import android.webkit.WebViewClient;

            public class WebActivity extends Activity{
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.web_layout);

                    WebView webView = (WebView) findViewById(R.id.web_view);

                    Intent intent = getIntent();
                    String url = intent.getStringExtra("url");

                    //加载
                    webView.loadUrl(url);

                    //设置
                    webView.setWebViewClient(new WebViewClient());

                    WebSettings settings = webView.getSettings();
                    settings.setJavaScriptEnabled(true);
                    settings.setJavaScriptCanOpenWindowsAutomatically(true);
                }
            }


            <---主页面跳转---->
            package com.example.a02_httpurlconnnection_newstop_03;

            import android.content.Context;
            import android.content.DialogInterface;
            import android.content.Intent;
            import android.net.ConnectivityManager;
            import android.net.NetworkInfo;
            import android.os.Bundle;
            import android.os.Handler;
            import android.os.Message;
            import android.provider.Settings;
            import android.support.v7.app.AlertDialog;
            import android.support.v7.app.AppCompatActivity;
            import android.util.Log;
            import android.view.View;
            import android.widget.AdapterView;
            import android.widget.ListView;

            import com.example.a02_httpurlconnnection_newstop_03.adapter.MyAdapter;
            import com.example.a02_httpurlconnnection_newstop_03.bean.DataBean;
            import com.example.a02_httpurlconnnection_newstop_03.bean.DataResultBean;
            import com.google.gson.Gson;

            import java.io.BufferedReader;
            import java.io.InputStream;
            import java.io.InputStreamReader;
            import java.net.HttpURLConnection;
            import java.net.URL;
            import java.util.List;

            public class MainActivity extends AppCompatActivity {

                private ListView listView;

                private Handler handler = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        //接收数据...设置适配器
                        if (msg.what == 0){
                            DataBean dataBean = (DataBean) msg.obj;

                            list = dataBean.getResult().getData();

                            //设置适配器

                            MyAdapter myAdapter = new MyAdapter(list, MainActivity.this);
                            listView.setAdapter(myAdapter);
                        }

                    }
                };
                private List<DataResultBean> list;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);

                    listView = (ListView) findViewById(R.id.list_view);
                    //条目的点击事件
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            //传值过去...url路径
                            if (list != null){
                                Intent intent = new Intent(MainActivity.this,WebActivity.class);

                                intent.putExtra("url",list.get(i).getUrl());
                                startActivity(intent);
                            }
                        }
                    });

                }

                public void getTop(View view){

                    //点击获取网络数据之前,判断一下网络是否可用...不可用,设置
                    if (isNetConnected()){
                        getNetData();

                    }else {
                        //对话框
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

                        builder.setTitle("警告");
                        builder.setMessage("网络不可用,是否设置?");

                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Settings.ACTION_WIRELESS_SETTINGS
                                //Settings.ACTION_WIFI_SETTINGS
                                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                                startActivity(intent);
                            }
                        });
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });

                        builder.show();

                    }

                }

                /**
                 * 判断网络是否可用
                 *
                 * boolean
                 */
                private boolean isNetConnected(){
                    //1.获取一个连接管理对象
                    ConnectivityManager manager = (ConnectivityManager) MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);

                    //2.获取网络连接的信息
                    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

                    if (networkInfo != null){
                        //返回值就代表网络是否可用
                        return networkInfo.isAvailable();
                    }

                    return false;
                }

                /**
                 * 获取头条的数据
                 */
                private void getNetData() {
                    new Thread(){
                        @Override
                        public void run() {
                            //头条服务器地址
                            String path = "http://v.juhe.cn/toutiao/index";

                            try {
                                URL url = new URL(path);

                                //打开连接
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                //设置
                                connection.setRequestMethod("POST");
                                connection.setConnectTimeout(5000);
                                connection.setReadTimeout(5000);

                                //post方式要提交参数给服务器...以流的方式提交给服务器
                                connection.setDoOutput(true);
                                //设置请求参数的类型
                                connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

                                String params = "type=top&key=597b4f9dcb50e051fd725a9ec54d6653";
                                //参数以流的形式写给服务器...字节数组的形式写出去
                                connection.getOutputStream().write(params.getBytes());

                                //响应
                                int responseCode = connection.getResponseCode();
                                if (responseCode == 200){
                                    //获取输入字节流
                                    InputStream inputStream = connection.getInputStream();

                                    String json = streamToString(inputStream,"utf-8");

                                    Log.i("json",json);
                                    //解析...解析完成之后发送到主线程,设置适配器
                                    Gson gson = new Gson();
                                    DataBean dataBean = gson.fromJson(json, DataBean.class);

                                    //发送出去
                                    Message message = Message.obtain();
                                    message.what = 0;
                                    message.obj = dataBean;
                                    handler.sendMessage(message);
                                }


                            } catch (Exception e) {
                                e.printStackTrace();
                            }


                        }
                    }.start();
                }

                private String streamToString(InputStream inputStream,String charset) {
                    try {
                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);

                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                        String s = null;
                        StringBuilder builder = new StringBuilder();
                        while ((s = bufferedReader.readLine()) != null){
                            builder.append(s);
                        }

                        bufferedReader.close();
                        return builder.toString();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return  null;
                }
            }
      <----清单列表---->
      <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.a02_httpurlconnnection_newstop_03">

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <activity android:name=".WebActivity"/>
        </application>

    </manifest>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值