1. 程式人生 > >Android---如何利用API實時獲取各頻道新聞?

Android---如何利用API實時獲取各頻道新聞?

基本上萬事俱備了,博主我把開發新聞閱讀器的相關知識都整理好了,接下來幾天我要搞一個新聞閱讀器(*^__^*) ~

本次例項包含了利用API(從“百度APIStore”上找的),從網路上實時獲取各種頻道的新聞。

接下來,我們首先建一個Layout,上面放一個Spinner,用來展現各種新聞頻道,而下面,我們放一個TextView,當選中Spinner中相應的頻道時,TextView中則會載入從網路獲取的該頻道實時新聞。

這裡先給大家貼個工具類,用來從網路獲取資訊:

public class UrlUtil {
    //獲取頻道的網路介面
    public static String channelUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/channel_news";
    //獲取頻道對應新聞的網路介面
    /*
    get 請求引數
    *channelId 新聞頻道id,必須精確匹配
     channelName 新聞頻道名稱,可模糊匹配
     title 新聞標題,模糊匹配
     page 頁數,預設1。每頁最多20條記錄
    *needContent 是否需要返回正文,1為需要,其他為不需要
    *needHtml 是否需要返回正文的html格式,1為需要,其他為不需要
     */
    public static String newsUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news";

}

Layout:

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    tools:context="jerehdu.com.jerehdu04.HttpNewsActivity"
    android:orientation="vertical">


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingRight="12dp">
            <Spinner
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:id="@+id/channel"
                android:gravity="center">
            </Spinner>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/news"/>
        </LinearLayout>

    </ScrollView>


</LinearLayout>


Activity:

public class HttpNewsActivity extends AppCompatActivity {

    private Spinner channel;
    private TextView show;
    private SimpleAdapter sa;
    private List<Map<String,String>> channelList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_news);
        channel = (Spinner) findViewById(R.id.channel);
        show = (TextView) findViewById(R.id.news);
        channelList = new ArrayList<>();
        sa = new SimpleAdapter(this,channelList,
                android.R.layout.simple_list_item_1,
                new String[]{"name"},new int[]{android.R.id.text1});
        channel.setAdapter(sa);
        String httpUrl = UrlUtil.channelUrl;
        new GetNewsChannel().execute(httpUrl);

        //Spinner監聽
        channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Map map = channelList.get(position);
                String channelName = (String) map.get("name");
                String channelId = (String) map.get(channelName);
                String[] strings = new String[]{channelId,channelName};
                new GetNews().execute(strings);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //獲取新聞頻道
    public class GetNewsChannel extends AsyncTask<String,Void,String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {
            return HttpUtil.HttpGet(strings[0]);
        }

        //在UI執行緒(主執行緒)中執行命令
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s.equals("")){
                Toast.makeText(getBaseContext(),"沒有資料",Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                JSONObject obj = new JSONObject(s);
                JSONObject body = obj.getJSONObject("showapi_res_body");
                JSONArray ja = body.getJSONArray("channelList");
                for(int i = 0;i<ja.length();i++){
                    JSONObject channelObj = (JSONObject) ja.get(i);
                    String id = channelObj.getString("channelId");
                    String name = channelObj.getString("name");
                    Map map = new HashMap();
                    map.put("name",name);
                    map.put(name,id);
                    channelList.add(map);
                }
                sa.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    //獲取新聞內容
    public class GetNews extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... params) {
            String httpUrl = UrlUtil.newsUrl;
            String httpArg = "channelId="+params[0]+"&" +
                    "channelName="+params[1]+"&" +
                    "title=&" +
                    "page=1&" +
                    "needContent=1&" +
                    "needHtml=1";
            String jsonResult = httpUrl + "?" + httpArg;
            return HttpUtil.HttpGet(jsonResult);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s.equals("")){
                show.setText("沒有資料或無網路連線");
            }else {
                jsonHandle(s);
            }
        }

    }

    //解析Json
    public void jsonHandle(String s){
        InputStream is ;
        BufferedReader reader = null;
        StringBuilder sbd = new StringBuilder();
        try {
            JSONObject obj = new JSONObject(s);
            JSONObject body = obj.getJSONObject("showapi_res_body");
            JSONObject body2 = body.getJSONObject("pagebean");
            JSONArray ja = body2.getJSONArray("contentlist");
            for(int i = 0;i<ja.length();i++){
                JSONObject newsObj = (JSONObject) ja.get(i);
                String news1 = newsObj.getString("content");
                sbd.append(news1);
                sbd.append("\t\n");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        show.setText(sbd.toString());
    }

}

預覽圖: