简单的AnsyTask的使用demo
1.定义一个模拟网络操作的类
package com.example.administrator.myapplication; /** * Created by Administrator on 2016/7/11. * 模拟网络环境 */ public class NetOperator { public void operation(){ try { //睡眠一秒 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
2.定义AsnyTask的类
package com.example.administrator.myapplication; import android.os.AsyncTask; import android.util.Log; import android.widget.ProgressBar; import android.widget.TextView; /** * Created by Administrator on 2016/7/11. * * 生成该类的对象,并调用execute方法之后 * 首先执行的是onProExecute方法 * 其次执行doInBackgroup方法 */ public class ProgressBarAsyncTask extends AsyncTask { private TextView textView; private ProgressBar progressBar; ProgressBarAsyncTask(TextView textView, ProgressBar progressBar) { super(); this.textView = textView; this.progressBar = progressBar; } @Override //被后台线程执行后,被UI线程被调用,一般用于初始化界面控件,如进度条 protected void onPreExecute() { super.onPreExecute(); Log.d("TEST","初始化操作"); } @Override //在PreExcute执行后被启动AysncTask的后台线程调用,将结果返回给UI线程 protected Object doInBackground(Object[] objects) { //这个方法执行多线程操作 NetOperator netOperator = new NetOperator(); int i = 0; for (i = 10; i <= 100; i += 10) { netOperator.operation(); publishProgress(i); } Log.d("TEST","后台执行多线程"); return i + objects.toString(); } @Override //执行完后由UI线程调用,用于更新界面操作 protected void onPostExecute(Object o) { textView.setText("异步执行操作结束!"); Log.d("TEST","多线程执行结束"); } @Override //更新进度条 protected void onProgressUpdate(Object[] values) { int value= (int) values[0]; progressBar.setProgress(value); Log.d("TEST","更新进度条"); } }
3.在Activity中使用
package com.example.administrator.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView myTextView; private ProgressBar myProcessBar; private Button myButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { myTextView = (TextView) findViewById(R.id.textView); myProcessBar = (ProgressBar) findViewById(R.id.progressBar); myButton = (Button) findViewById(R.id.button); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ProgressBarAsyncTask progressBarAsyncTask=new ProgressBarAsyncTask(myTextView,myProcessBar); progressBarAsyncTask.execute(1000); } }); } }
时间: 2024-10-11 03:27:58