用异步任务实现简单的新闻资讯

来源:互联网 发布:mac怎么创建网页 编辑:程序博客网 时间:2024/05/16 01:17

程序中用到的有接口回调,接口回调在开发中是很重要的,能解决很多问题,如果有不懂得,可以继续关注我的博客,部分博客中有我对于接口回调的理解,我会后续会写更多的博客,我的技术有限,所以代码都是以简单的为主,异步任务有不懂得,我的博客也有关于异步任务的一些介绍
值得注意的是:本程序的接口并没有写,读者可自己寻找适合的接口进行操作

新闻资讯的基本布局

<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"    tools:context="${packageName}.${activityClass}" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="新闻标题:" />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="请点击:" />        <Spinner            android:id="@+id/sp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:background="@null" />    </LinearLayout>    <View        android:layout_width="match_parent"        android:layout_height="20dp"        android:background="#00BFFF" />    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="10px"        android:text="新闻内容:" />    <TextView        android:id="@+id/te"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></LinearLayout>

封装好的异步任务工具类

import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import javax.security.auth.PrivateCredentialPermission;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.widget.ImageView;public class PottingAsyncTask extends AsyncTask<String, Void, Object> {    private OnDownLitener onDownLitener;    private DownType downType;    public PottingAsyncTask(DownType downType) {        // TODO Auto-generated constructor stub        this.downType = downType;    }    //子线程    @Override    protected Object doInBackground(String... arg0) {        // TODO Auto-generated method stub        byte[] bs = getByteArray(arg0[0]);        if (bs != null) {            switch (downType) {            case JSON:                String json = new String(bs);                if(onDownLitener!=null){                                        Object datasObject=onDownLitener.downJson(json);                    return datasObject;                }                break;            case IMAGE:                Bitmap bitmap = BitmapFactory.decodeByteArray(bs, 0, bs.length);                return bitmap;            default:                break;            }        }        return null;    }    //在执行完doInBackground后再执行onPostExecute    @Override    protected void onPostExecute(Object result) {        switch (downType) {        case JSON:            if(onDownLitener!=null){                onDownLitener.paresJson(result);            }            break;        case IMAGE:            if(onDownLitener!=null){                onDownLitener.setImage(result);            }            break;        default:            break;        }    }    //构建接口,使用接口回调的方式控制控件    public interface OnDownLitener{        Object downJson(String json);//用于下载json        void paresJson(Object object);//用于解析json        void setImage(Object object);//用于控制image控件    }    //获得byte数组    private byte[] getByteArray(String urlString) {        InputStream in = null;        ByteArrayOutputStream ou = null;        URL url;        try {            url = new URL(urlString);            HttpURLConnection httpURLConnection = (HttpURLConnection) url                    .openConnection();            httpURLConnection.setRequestMethod("GET");            httpURLConnection.setReadTimeout(3000);            httpURLConnection.connect();            if (httpURLConnection.getResponseCode() == 200) {                in = httpURLConnection.getInputStream();                ou=new ByteArrayOutputStream();                byte[] buffer = new byte[1024 * 8];                int len = -1;                while ((len = in.read(buffer)) != -1) {                    ou.write(buffer, 0, len);                }                return ou.toByteArray();            }        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally {            if (in != null) {                try {                    in.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if (ou != null) {                try {                    ou.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }        return null;    }    //借助泛型,确定所需要的类型    public static enum DownType {        JSON, IMAGE    }    //接口回调的方法    public PottingAsyncTask setOnDownLitener(OnDownLitener onDownLitener) {        this.onDownLitener = onDownLitener;        return this;//返回this的原因是链式编程,返回当前PottingAsyncTask的对象    }}

新闻资讯的主方法

import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import com.example.day06_04.PottingAsyncTask.DownType;import com.example.day06_04.PottingAsyncTask.OnDownLitener;import android.R.integer;import android.app.Activity;import android.graphics.Bitmap;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.Spinner;import android.widget.TextView;public class MainActivity extends Activity {    //需要自己填写自己所需要的新闻接口    String urlString="";    private Spinner spinner=null;    private TextView textView=null;    private ArrayAdapter<String> adapter=null;    private List<Map<String, Object>> listmap=new ArrayList<Map<String,Object>>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView=(TextView) findViewById(R.id.te);        spinner=(Spinner) findViewById(R.id.sp);        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {            @Override            public void onItemSelected(AdapterView<?> arg0, View arg1,                    int arg2, long arg3) {                // 判断是否等于空的原因是因为网络加载时需要时间的,防止程序报错                if(listmap!=null){                    String dString=(String) listmap.get(arg2).get("summary");                    textView.setText(dString);                  }            }            @Override            public void onNothingSelected(AdapterView<?> arg0) {            }        });        new PottingAsyncTask(DownType.JSON).setOnDownLitener(new OnDownLitener() {            @Override            public void paresJson(Object object) {                // TODO Auto-generated method stub                List<String> list =(List<String>) object;                adapter=new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,list);                spinner.setAdapter(adapter);            }            @Override            public Object downJson(String json) {                // TODO Auto-generated method stub                try {                //不同的接口,获得不同的json,所以解析json的代码也是不一样的,可以仿造这部分的代码                    List<String> list=new ArrayList<String>();                    JSONObject jsonObject=new JSONObject(json);                    JSONArray jsonArray=jsonObject.getJSONArray("data");                    for(int i=0;i<jsonArray.length();i++){                    //利用Map原因是map可以存储更多类型的数据                        Map<String, Object> map=new HashMap<String, Object>();                        String title = jsonArray.getJSONObject(i).getString("title");                        String summary = jsonArray.getJSONObject(i).getString("summary");                        int len=i+1;                        list.add("【"+len+"】:"+title);                        map.put("title", title);                        map.put("summary", summary);                        listmap.add(map);                    }                    return list;                                } catch (JSONException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                return null;            }            @Override            public void setImage(Object object) {                // TODO Auto-generated method stub            }        }).execute(urlString);    }}
0 0
原创粉丝点击