threads in adnroid.png
In this post I show the code for using a thread and an asynctask in Android. 
It will help you to further understand how helpful these features are.

First of all, I set up the code with 6 nested child views with a progressBar, buttons and textViews.

</pre>
<pre><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="horizontal">

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/format4"
        android:id="@+id/relativelayout1"
        android:layout_alignParentTop="true">

        <ProgressBar
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="290dp"
            android:layout_height= "26dp"
            android:id="@+id/pbarProgreso"
            android:layout_marginTop="15dp"
            android:layout_marginStart="10dp"

            android:progressTint="#b20d8b"/>

    </RelativeLayout>

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:background="@drawable/format4"
        android:id="@+id/relativelayout2"
        android:layout_below="@+id/relativelayout1">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/btnSinHilos"
            android:background="@drawable/format_buttons"
            android:layout_marginTop="15dp"
            android:layout_alignParentStart="true"
            android:layout_marginStart="15dp"
            android:layout_marginEnd="10dp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Without Thread"
            android:id="@+id/textView1"
            android:textColor="#000000"
            android:textSize="23sp"

            android:layout_toEndOf="@+id/btnSinHilos"
            android:layout_centerInParent="true"
             />

    </RelativeLayout>

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:background="@drawable/format4"
        android:id="@+id/relativelayout3"
        android:layout_below="@+id/relativelayout2">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/btn_thread"
            android:background="@drawable/format_buttons"
            android:layout_alignParentStart="true"
            android:layout_marginStart="15dp"
            android:layout_centerInParent="true"
            android:layout_marginTop="15dp"
            android:layout_marginEnd="10dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="With Thread"
            android:id="@+id/textView2"
            android:textColor="#000000"
            android:textSize="23sp"

            android:layout_toEndOf="@+id/btn_thread"
            android:layout_centerInParent="true"
            />

    </RelativeLayout>

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:background="@drawable/format4"
        android:id="@+id/relativelayout4"
        android:layout_below="@+id/relativelayout3">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/btn_async"
            android:background="@drawable/format_buttons"
            android:layout_alignParentStart="true"
            android:layout_marginStart="15dp"
            android:layout_marginEnd="10dp"

            android:layout_centerInParent="true"
            android:layout_marginTop="15dp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Async Task"
            android:id="@+id/textView3"
            android:textColor="#000000"
            android:textSize="23sp"
            android:layout_toEndOf="@+id/btn_async"
            android:layout_centerInParent="true"
            />

    </RelativeLayout>

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:background="@drawable/format4"
        android:id="@+id/relativelayout5"
        android:layout_below="@+id/relativelayout4">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/cancel_btn"
            android:background="@drawable/format_buttons"
            android:layout_alignParentStart="true"
            android:layout_marginStart="15dp"
            android:layout_centerInParent="true"
            android:layout_marginTop="15dp"
            android:layout_marginEnd="10dp"

            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cancel Async Task"
            android:id="@+id/textView4"
            android:textColor="#000000"
            android:textSize="23sp"

            android:layout_toEndOf="@+id/cancel_btn"
            android:layout_centerInParent="true"
            />

    </RelativeLayout>

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:background="@drawable/format4"
        android:id="@+id/relativelayout6"
        android:layout_below="@+id/relativelayout5">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/btnAsyncDialog"
            android:layout_centerInParent="true"
            android:background="@drawable/format_buttons"
            android:layout_marginTop="15dp"
            android:layout_marginEnd="10dp"
            android:layout_alignParentStart="true"
            android:layout_marginStart="15dp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Async Task and Progress Dialog"
            android:id="@+id/textView5"
            android:textColor="#000000"
            android:textSize="23sp"
            android:layout_toEndOf="@+id/btnAsyncDialog"
            android:layout_centerInParent="true"
            />

    </RelativeLayout>

</RelativeLayout></pre>
<pre>
Then, I used an asyncTask to perform a refreshing task within a progress bar and a progress dialog.
package com.example.android.threads_hilos_bases;

public class MainActivity extends ActionBarActivity {

    ProgressBar pbarProgreso ; //Si pongo esto adentro de onCreate el scope no sirve
    //porque mi función va dentro de mainActivity y se está actualizando durante la actividad

    MiTareaAsincrona doSomethingAsynchronous ; //Si pongo esto adentro de onCreate el scope no sirve
    //porque mi función va dentro de mainActivity

    MiTareaAsincronaDialog tarea2 ;

    ProgressDialog pDialog ;
    Button cancel_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnSinHilos = (Button) findViewById(R.id.btnSinHilos);
        pbarProgreso = (ProgressBar) findViewById(R.id.pbarProgreso);

        Button btnThread = (Button) findViewById(R.id.btn_thread);
        Button btnAsync  = (Button) findViewById(R.id.btn_async);
         cancel_btn =(Button) findViewById(R.id.cancel_btn);
        Button btnAsyncDialog = (Button) findViewById(R.id.btnAsyncDialog);

        cancel_btn.setEnabled(false);

Now, the extended clases are showed so that the asynchronous task can be performed.

/*
 ** Tarea asíncrona sin diálogo que actualiza los valores del ProgressBar
 */
        private class MiTareaAsincrona extends AsyncTask&lt;Void, Integer, Boolean&gt; {

        @Override
        protected Boolean doInBackground(Void... params) {

            for(int i=1; i&lt;=10; i++) {
                tareaLarga();

                publishProgress(i*10);

                if(isCancelled())
                    break;
            }
            return true;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            int progreso = values[0].intValue();

            pbarProgreso.setProgress(progreso);
        }

        @Override
        protected void onPreExecute() {
            cancel_btn.setEnabled(true);
            pbarProgreso.setMax(100);
            pbarProgreso.setProgress(0);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if(result)
                Toast.makeText(MainActivity.this, "Tarea finalizada!",
                        Toast.LENGTH_SHORT).show();
            cancel_btn.setEnabled(false);
        }

        @Override
        protected void onCancelled() {
            Toast.makeText(MainActivity.this, "Tarea cancelada!",
                    Toast.LENGTH_SHORT).show();

            cancel_btn.setEnabled(false);
        }
      }

    /*
    ** Tarea asíncrona con diálogo que actualiza los valores del ProgressBar
    */
    private class MiTareaAsincronaDialog extends AsyncTask&lt;Void, Integer, Boolean&gt; {

        @Override
        protected void onPreExecute() {
            pDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    MiTareaAsincronaDialog.this.cancel(true);
                }
            });

            pDialog.setProgress(0);
            pDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... params) {

            for(int i=1; i&lt;=10; i++) {
                tareaLarga();

                publishProgress(i*10);

                if(isCancelled())
                    break;
            }
            return true;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            int progreso = values[0].intValue();

            pDialog.setProgress(progreso);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if(result)
            {
                pDialog.dismiss();
                Toast.makeText(MainActivity.this, "Tarea finalizada!",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onCancelled() {
            Toast.makeText(MainActivity.this, "Tarea cancelada!",
                    Toast.LENGTH_SHORT).show();
        }
    }
    /*
    ** Operación de larga duración que espera un segundo
    */
    private void tareaLarga() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }

}</pre>
<pre>
Finally I show you  a screenshot with the finished app and in some days I will show you an url with the video.
 threads

Sources:

[1] http://www.sgoliver.net/blog/tareas-en-segundo-plano-en-android-i-thread-y-asynctask/

[2] http://stackoverflow.com/questions/11305382/border-for-the-layout

[3] https://developer.android.com/reference/java/lang/Runnable.html

[4] https://en.support.wordpress.com/code/posting-source-code/

[6] https://amatellanes.wordpress.com/2013/03/11/insertar-codigo-fuente-en-wordpress/

 

Anuncios