首页 > 代码库 > Async异步处理
Async异步处理
MyAsync
1 package com.zhangmeng.xml; 2 3 import android.os.AsyncTask; 4 import android.widget.ProgressBar; 5 import android.widget.TextView; 6 7 /** 8 * Created by zhangmeng on 2016/10/6. 9 */10 11 public class MyAsync extends AsyncTask<Integer,Integer,String> {12 private ProgressBar bar;13 private TextView tv;14 15 public MyAsync(ProgressBar bar,TextView tv) {16 super();17 this.bar = bar;18 this.tv=tv;19 }20 21 @Override22 protected void onPreExecute() {23 super.onPreExecute();24 tv.setText("The file is downloading! Please wait....");25 }26 27 28 29 30 31 @Override32 protected String doInBackground(Integer... params) {33 DelayOperator delayOperator=new DelayOperator();34 int i;35 for (i = 1; i <1000000; i++) {36 delayOperator.delay(params[0]);37 publishProgress(i);38 }39 40 return i + params[0].intValue() + "";41 }42 43 44 @Override45 protected void onProgressUpdate(Integer... values) {46 bar.setProgress(values[0]);47 48 }49 }
1 package com.zhangmeng.xml; 2 import android.support.v7.app.AppCompatActivity; 3 import android.os.Bundle; 4 import android.view.View; 5 import android.widget.Button; 6 import android.widget.ProgressBar; 7 import android.widget.TextView; 8 9 public class MainActivity extends AppCompatActivity {10 11 private Button bt;12 private TextView textView;13 private ProgressBar bar;14 15 @Override16 protected void onCreate(Bundle savedInstanceState) {17 super.onCreate(savedInstanceState);18 setContentView(R.layout.activity_main);19 bt= (Button) findViewById(R.id.btn);20 textView=(TextView) findViewById(R.id.tv);21 bar=(ProgressBar) findViewById(R.id.pb);22 bt.setOnClickListener(new View.OnClickListener() {23 @Override24 public void onClick(View v) {25 MyAsync async=new MyAsync(bar,textView);26 async.execute(100);27 }28 });29 30 31 32 }33 34 35 36 }
delay
1 package com.zhangmeng.xml; 2 3 /** 4 * Created by zhangmeng on 2016/10/5. 5 */ 6 7 public class DelayOperator { 8 public void delay(int time){ 9 try {10 Thread.sleep(time);11 } catch (InterruptedException e) {12 e.printStackTrace();13 }14 }15 }
Async异步处理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。