new Thread(new Runnable() {
public void run() {
int i = 0;
while (i < 10000) {
Thread.sleep(1000);
Log.v(”thread”,”awake”);
i += 1000;
}
}
}).start();
Thread th = new Thread(..... );
th.start(); th.interrupt();
public void onClick(View v) {
MyTask task = new MyTask();
task.execute(4);
task.cancel();
}
private class MyTask extends AsyncTask<Integer, Integer, String> {
@Override
protected String doInBackground(Integer... param) {
//hacer operaciones
publishProgress(int); //actualizar progreso
return resultado;
}
@Override
protected void onPostExecute(String result) {
tView.setText(result); //dialog, toast.. lo que queramos
super.onPostExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values[0]);
Log.i( ”task", ”progress update: " + String.valueOf( values[0] ) );
}
@Override
protected void onPreExecute() { //inicializaciones
Log.i( "task", "on preExecute" );
super.onPreExecute();
}
@Override
protected void onCancelled() { //fin
Log.i( "task", "on cancelled" );
super.onCancelled();
}
}
Mejora de la clase Service, implementaciones
por defecto y threads:
Crea un thread para ejecutar todos los intents que lleguen a onStartCommand()
Cola de trabajo para todos los intents, se envían uno a uno a onHandleIntent()
Se para solo mediante stopSelf() cuando acaba
Implementación por defecto de onBind(), return null
Implementación por defecto de onStartCommand(),
que envía los Intent a la función onHandleIntent()