带有对话框(范例)的Android异步任务
Xn_warm
・5 分钟阅读
AsyncTask可以正确,方便地使用UI线程。
AsyncTask被设计成一个围绕线程和Handler的helper类,不构成通用线程框架,理想情况下,AsyncTasks应该用于短操作(最多几秒)。如果需要保持线程长时间运行,强烈建议您使用java.util.concurrent pacakge提供的各种API,例如 Executor,ThreadPoolExecutor和FutureTask。
详细阅读http://developer.android.com/reference/android/os/AsyncTask.html
异步任务允许在后台处理长任务,从而释放UI线程。
LongTask.java
public class LongTask extends AsyncTask<Void, Void, Boolean>
{
private Context ctx;
private String TAG="LongTask.java";
private String url;
private ProgressDialog p;
private String filename;
private ImageView i;
private Bitmap bitmap;
/*
Constructor
*/
public LongTask(String fileurl,String filename,ImageView i,Context ctx)
{
Log.v(TAG,"Url Passed");
this.url=fileurl;
this.ctx=ctx;
this.filename=filename;
this.p=new ProgressDialog(ctx);
this.i=i;
this.bitmap=null;
}
/*
Runs on the UI thread before doInBackground
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
p.setMessage("Saving image to SD Card");
p.setIndeterminate(false);
p.setProgressStyle(ProgressDialog.STYLE_SPINNER);
p.setCancelable(false);
p.show();
}
/*
This method to perform a computation on a background thread.
*/
@Override
protected Boolean doInBackground(Void... voids) {
/*
1. Instantiate file class and pass the directory and subdirectory
SDCARD/PICTURES/Test
*/
File location = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Test");
/*
2. Create Directory Test with File object media
*/
if (!location.exists()) {
if (!location.mkdirs()) {
Log.v(TAG,"Directory was not created");
return null;
}
}
/*
3. Begin HTTP download
*/
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.v("FIle download error","Error.Status.Code ->" + statusCode +" from url ->"+ url);
return false;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
bitmap = BitmapFactory.decodeStream(inputStream);
File thumburl = new File(location, filename+".jpg");
try {
File file = new File(thumburl.getPath());
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fOut);
fOut.flush();
fOut.close();
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
}
finally
{
if (inputStream != null)
{
inputStream.close();
}
entity.consumeContent();
}
}
}
catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e(TAG,"Image download error->"+ e.toString());
}
return false;
}
/*
Runs on the UI thread after doInBackground
*/
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
p.dismiss();
if(result)
{
// Do something awesome here
Toast.makeText(ctx,"Download complete", Toast.LENGTH_SHORT).show();
i.setImageBitmap(bitmap);
}
else
{
Toast.makeText(ctx,"Download failed, network issue",Toast.LENGTH_SHORT).show();
}
}
}
MyActivty.java
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void GetFile(View view)
{
ImageView i=(ImageView)findViewById(R.id.imageView);
String fileUrl="http://25.media.tumblr.com/d55a509993790027240311c9f611aaf8/tumblr_n0hpzpKEfE1st5lhmo1_1280.jpg";
LongTask l=new LongTask(fileUrl,"my_large_download_test.jpg",i,MyActivity.this);
l.execute();
}
}
结果
完整源码
https://drive.google.com/file/d/0B8MVe8jYOYOSS2oxa09vM01YSk0/edit?usp=sharing
我的安装程序是IntelliJ 13.0,在LG Optimus G上使用Android SDK 19.0(4.4.2)测试
enjoy!