Tarefa assíncrona Android com caixa de diálogo

AsyncTask permite o uso adequado e fácil do thread de interface do usuário. Esta classe permite realizar operações em segundo plano e publicar resultados no thread de UI sem ter que manipular threads e / ou manipuladores.

AsyncTask foi projetado para ser uma classe auxiliar em torno de Thread e Handler e não constitui uma estrutura de threading genérica. AsyncTasks devem ser usados ​​idealmente para operações curtas (alguns segundos no máximo). Se você precisar manter os threads em execução por longos períodos de tempo, é altamente recomendável usar as várias APIs fornecidas pelo pacote java.util.concurrent, como Executor, ThreadPoolExecutor e FutureTask.

Leia mais aqui http://developer.android.com/reference/android/os/AsyncTask.html

A tarefa assíncrona permite que uma tarefa longa seja processada em segundo plano, liberando assim o thread de interface do usuário.

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();

}
}

Resultado

CenárioCenárioCenário

Full Source

https://drive.google.com/file/d/0B8MVe8jYOYOSS2oxa09vM01YSk0/edit?usp=sharing

Minha configuração é IntelliJ 13.0 com teste Android SDK 19.0 (4.4.2) no LG Optimus G

Esse é meu primeiro post … divirta-se!