AsyncTask的使用代码

public class MainActivity extends AppCompatActivity {

    private ListView listview;
    private String myutrp="http://api.tianapi.com/social/?key=9ae87ac342f61fe405423fa5db830b54&num=10";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取资源id
        listview = findViewById(R.id.listview);

        // 调用异步任务
        MyTask myTask = new MyTask();
        myTask.execute(myutrp);


    }
    /**
     * 泛型类
     * params1:请求的网络地址  String  Void
     * params2:网络请求的进度   Integer Void
     * params3:服务器返回的数据类型   String Bitmap Void
     */
    class MyTask extends AsyncTask<String,Integer,String>{
        //在后台运行
        @Override
        protected String doInBackground(String... strings) {//String... 可变长的字符串  string类型的数组,长度不固定
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setConnectTimeout(5000);
                urlConnection.setReadTimeout(5000);

                if (urlConnection.getResponseCode()==200){
                    InputStream inputStream = urlConnection.getInputStream();
                    //将流转换成String
                    String s = StreamToString(inputStream);
                    return s;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        //更新进度
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);

        }
        //用于用户提示
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(MainActivity.this,"正在请求网络,..请稍后",Toast.LENGTH_SHORT).show();
        }
        //在doInBackground之后,调用的方法,,,更新UI的操作,相当于handlerMessage中的功能
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //解析展示
            Gson gson = new Gson();
            RestData restData = gson.fromJson(s, RestData.class);
            List<RestData.NewslistBean> list = restData.getNewslist();

            //创建适配器
            MyAdapter myAdapter = new MyAdapter(MainActivity.this, list);
            listview.setAdapter(myAdapter);

        }
    }
    //将流转换成String
    private String StreamToString(InputStream stream){
        StringBuilder builder = new StringBuilder();
        String str;
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        try {
            while ((str=reader.readLine())!=null){
                    builder.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页