Recupero valore da Asynctask

Recupero valore da Asynctask

Recupero valore da Asynctask

Uno dei modi per sapere quando un task asincrono termina la sua esecuzione è implementare un listener. Un altro modo è utilizzare il metodo GET.
LISTENER: non blocca il thread principale ed è quindi possibile eseguire altre operazioni. Per prima cosa bisogna definire l’interfaccia. Il metodo dell’intefaccia sarà chiamato quando il task termina l’esecuzione e deve essere implementato nell’Activity principale.
GET: blocca il thread principale e quindi non è possibile eseguire altre operazioni.

Scriviamo l’intefaccia onTaskCompleted.java che accetta un valore intero in ingresso

 
public interface OnTaskCompleted{
    void onTaskCompleted(int pValue);
}

L’Activity principale che lancia il task asincrono: MainActivity.java

package it.space_service.example.asynctask;


import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnTaskCompleted {
	TextView mTxtMessage = null;
	Button mBtnAvvio = null;
	Button mBtnGetWithTime = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mTxtMessage = (TextView) findViewById(R.id.txtMsg);
		mBtnAvvio= (Button) findViewById(R.id.btnAvvio);
		mBtnAvvio.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new MyAsyncTask(MainActivity.this, MainActivity.this, 0).execute();
			}
		});
		mBtnGetWithTime= (Button) findViewById(R.id.btnGetWithTime);
		mBtnGetWithTime.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					int ret = new MyAsyncTask(MainActivity.this,MainActivity.this, 1).execute().get(10000, TimeUnit.MILLISECONDS);
					mTxtMessage.setText("GET: Finito, valore di ritorno: "+ret);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ExecutionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (TimeoutException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	@Override
	public void onTaskCompleted(int pValue) {
		// TODO Auto-generated method stub
		mTxtMessage.setText("LISTENER: Finito, valore di ritorno: "+pValue);
	}
	public class MyAsyncTask extends AsyncTask{ //change Object to required type
		private OnTaskCompleted mListener 	= null;
		private ProgressDialog mDialog 		= null; 
		private boolean finish 				= false;
		private int value 					= 0;
		private int action 					= 0; //listener - 1 get
		public MyAsyncTask(OnTaskCompleted pListener, Context pContext, int pAction){
			this.mListener=pListener;
			this.mDialog = new ProgressDialog(pContext);
			this.action = pAction;
		}
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			this.mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			this.mDialog.setTitle("Titolo progress dialog");
			this.mDialog.setMessage("Task in run");
			this.mDialog.setCancelable(false);
			this.mDialog.setCanceledOnTouchOutside(false);
			this.mDialog.setIndeterminate(true);
			this.mDialog.setIcon(R.drawable.ic_launcher);
			this.mDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Termina", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish=true;
				}
			});	
			this.mDialog.show();
		}
		@Override
		protected Integer doInBackground(Object... params) {
			// TODO Auto-generated method stub
			while (!finish){
				publishProgress(value+=1);
				try {
					Thread.sleep(1000);
				} catch (Exception e) {
					e.getLocalizedMessage();
				}
				//se action = 1 (GET) esce dopo 5 secondi
				if (action==1 && value==5)
					return value;
			}
			return -1;
		}
		@Override
		protected void onProgressUpdate(Object... values) {
			mDialog.setMessage("Progress: "+((Integer)values[0]));
		};
		@Override
		protected void onPostExecute(Integer o){
			if (action==0)
				mListener.onTaskCompleted(value);
			if (mDialog.isShowing())
				mDialog.dismiss();
		}
	}
}

Layout XML: activity_main.xml



    

    

9 thoughts on “Recupero valore da Asynctask

  1. Moses

    That is a great tip particularly too those fresh to the blogosphere.
    Simple but very precise information… Thank you for sharing this one.
    A must read post!

  2. Best dating sites

    I think this is among the most significant info for me.
    And i am glad reading your article. But want to remark on few general
    things, The web site style is great, the articles is really
    excellent : D. Good job, cheers

  3. best price on kitchen faucets

    Oh my goodness! Impressive article dude! Thank you so much,
    However I am encountering problems with your RSS.
    I don’t know the reason why I can’t subscribe to it. Is there anybody else
    getting the same RSS issues? Anyone who knows the solution can you kindly respond?

    Thanks!!

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *