Android中AsyncTask异步加载
16lz
2021-01-24
AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程.
使用的优点:
l 简单,快捷
l 过程可控
在复杂的数据更新时,建议使用Handler。。下面是一个简单的例子:
.xml文件:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.example.administrator.asynctaskjson.MainActivity" tools:showIn="@layout/activity_main"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="AsyncTaskClick" android:text="AsyncTask异步加载json数据" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/resulttext" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="这里是接收到的数据内容" /> </LinearLayout></LinearLayout>
MainActivity.java
import android.os.AsyncTask;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends AppCompatActivity { private TextView resulttext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); resulttext = (TextView) this.findViewById(R.id.resulttext); } /** * 异步加载数据的实现 * * @param v */ public void AsyncTaskClick(View v) { new MyAsyncTask().execute(); } /** * 注意:1、在doInBackground方法中的参数类型必须和onPostExecute方法中的参数类型相同(在此处设置的为String类型) * 2、doInBackground方法的返回值和onPostExecute方法中的参数类型相同,onPostExecute方法中的参数就是doInBackground方法中的返回值 * 3、在doInBackground方法中,属于子线程,不能访问UI线程中的组件 */ class MyAsyncTask extends AsyncTask<String, Integer, String> { //在请求发起前触发的事件方法,一般做一些初始化的工作 // 在这里提示一下开始请求数据 @Override protected void onPreExecute() { Toast.makeText(MainActivity.this, "开始请求", Toast.LENGTH_SHORT).show(); super.onPreExecute(); } //在这里实现一些耗时的操作,比如请求网络数据,这里模拟请求到的数据 @Override protected String doInBackground(String... params) { return "我是请求到的数据"; } //请求结束后触发的事件方法,做一些更新UI,解析数据的操作。 @Override protected void onPostExecute(String result) { resulttext.setText(result); Toast.makeText(MainActivity.this, "请求完成", Toast.LENGTH_SHORT).show(); super.onPostExecute(result); } }}
更多相关文章
- 绘图机制
- Android中AlarmManager的使用
- Android艺术开发探索第三章——View的事件体系(上)
- [置顶] 【Android(安卓)Training】置顶索引
- (原创)Android入门教程(十五)之-- Activity生命周期及其配置使用
- Android(安卓)Input Framework(二)---EventHub
- Android的swift语言-Kotlin(一)
- Android中Handler问题汇总
- Android(安卓)sqlite 使用框架