本文主要是介绍Android之AsyncTask的使用(二)之文件下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
声明: 本人菜鸟一枚, 本博客是本人自学的内容, 适用于初学者, 不喜勿喷, 谢谢大家
-
-
- 下载案例
- AsyncTask准则
-
通过上一篇博客我们学习到了AsyncTask的主要作用, 那今天就写一个实际的例子: 文件下载
下载案例
在开始下载代码之前, 我们需要在清单文件中先加上权限!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.INTERNET"/>
DownloadActivity .java
public class DownloadActivity extends AppCompatActivity {private ProgressBar progressBar;private ImageView imageView;private static final int FILE_SIZE = 0;private static final int DOWNLOAD_PROGRESS = 1;private static final int DOWNLOAD_SUCCESS = 2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_download);progressBar = (ProgressBar) findViewById(R.id.progressBar);imageView = (ImageView) findViewById(R.id.imageView);}public void downloadClick(View view){new DownloadAsyncTas(this).execute("http://tupian.enterdesk.com/2013/mxy/10/12/5/1.jpg");}private static class DownloadAsyncTas extends AsyncTask<String, Integer, Integer>{private DownloadActivity activity;public DownloadAsyncTas(DownloadActivity activity) {this.activity = activity;}@Overrideprotected void onPreExecute() {super.onPreExecute();//先将其进度设置为0activity.progressBar.setProgress(0);}@Overrideprotected Integer doInBackground(String... params) {//完成下载任务String s = params[0];//这是从execute方法中传过来的参数, 即下载的地址try {URL url = new URL(s);HttpURLConnection conn = (HttpURLConnection) url.openConnection();int size = conn.getContentLength();//获取到最大值之后设置到进度条的MAXpublishProgress(FILE_SIZE, size);//开始下载byte[] bytes = new byte[10];//为方便测试故将其设置较小int len = -1;InputStream in = conn.getInputStream();FileOutputStream out = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "img.jpg");while( (len = in.read(bytes)) != -1 ){out.write(bytes, 0, len);publishProgress(DOWNLOAD_PROGRESS, len);out.flush();}out.close();in.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return DOWNLOAD_SUCCESS;}@Overrideprotected void onProgressUpdate(Integer... values) {super.onProgressUpdate(values);switch (values[0]){case FILE_SIZE:activity.progressBar.setMax(values[1]);break;case DOWNLOAD_PROGRESS:activity.progressBar.incrementProgressBy(values[1]);break;}}@Overrideprotected void onPostExecute(Integer integer) {super.onPostExecute(integer);if(integer == DOWNLOAD_SUCCESS){activity.imageView.setImageURI(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "img.jpg"));}}}}
效果图:
AsyncTask准则
- AsyncTask的实例必须在UI 线程中创建
- execute方法必须在UI线程中调用
- 不要手动的调用onPreExecute, doInBackground, onProgressUpdate, onPostExecute这几个方法
- 该Task只能执行一次, 否则多次调用会出现异常
- AsyncTask不能完全取代线程. 在些较为复杂或者后台反复执行的逻辑就可能需要线程和Handler来实现了
座右铭: 少说话, 多做事
这篇关于Android之AsyncTask的使用(二)之文件下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!