Progress Dialog et mode AsynChrone

Icône animée à la place d’une « progress bar » :
1°) créer une icône animée :
Créez un fichier XML de type « animated » dans le répertoire Drawable
 <?xml version="1.0" encoding="utf-8"?>  
 <animation-list xmlns:android="http://schemas.android.com/apk/res/android">  
   <item android:drawable="@drawable/micro_1" android:duration="200" />  
   <item android:drawable="@drawable/micro_2" android:duration="200" />  
   <item android:drawable="@drawable/micro_3" android:duration="200" />  
   <item android:drawable="@drawable/micro_4" android:duration="200" />  
   <item android:drawable="@drawable/micro_3" android:duration="200" />  
   <item android:drawable="@drawable/micro_2" android:duration="200" />  
 </animation-list>  

 

2°) créer un layout avec une imageview :

<ImageView
    android:id="@+id/mic_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="198dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/micro_1"
    />

3°) associer à une progress bar dans l’activity :

package com.andrologiciels.testanimatedicon;

import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    ProgressDialog progressBar;
    private int progressBarStatus = 0;
    private Handler progressBarHandler = new Handler();
    private ImageView micButton;
    //-- for testing progress bar
    private long fileSize = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //-- declare animation
        final AnimationDrawable[] rocketAnimation = new AnimationDrawable[1];
        final ImageView micButton = findViewById(R.id.mic_button);
        micButton.setBackgroundResource(R.drawable.micro_1);
        //-- button listener
        micButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //-- init button with animation
                micButton.setBackgroundResource(R.drawable.mic_image);
                rocketAnimation[0] = (AnimationDrawable) micButton.getBackground();
                startprogress(rocketAnimation[0]);
            }
        });
    }


    public void startprogress(final AnimationDrawable rocketAnimation) {
         rocketAnimation.start();
        progressBar = new ProgressDialog(MainActivity.this);
         //--reset filesize for demo
        fileSize = 0;
        //-- thread for demo
        new Thread(new Runnable() {
            public void run() {
                while (progressBarStatus < 100) {
                    // process some tasks
                    progressBarStatus = doSomeTasks();
                    // your computer is too fast, sleep 1 second
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // Update the progress bar
                    progressBarHandler.post(new Runnable() {
                        public void run() {
                            progressBar.setProgress(progressBarStatus);
                        }
                    });
                }

                // ok, file is downloaded,
                if (progressBarStatus >= 100) {
                    // sleep 2 seconds, so that you can see the 100%
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // close the progress bar dialog
                    progressBar.dismiss();
                    if(rocketAnimation.isRunning()){
                        rocketAnimation.stop();
                    }
                }
            }
        }).start();

    }

    // file download simulator... a really simple
    public int doSomeTasks() {

        while (fileSize <= 1000000) { //1000000

            fileSize++;

            if (fileSize == 100000) {
                return 10;
            } else if (fileSize == 200000) {
                return 20;
            } else if (fileSize == 300000) {
                return 30;
            } else if (fileSize == 400000) {
                return 40;
            } else if (fileSize == 500000) {
                return 50;
            } else if (fileSize == 600000) {
                return 60;
            }
        }

        return 100;
    }
}
Références :
Pour créer une fenêtre avec un cercle tournant indiquant que la tâche à réaliser s’exécute et que l’utilisateur doit attendre :

Avant de lancer la tâche

		final ProgressDialog pDialog = new ProgressDialog(this);
		pDialog.setMessage("Loading...");
		pDialog.show();
A la fin de l’exécution de la tâche :
pDialog.hide();
Pour créer un « Splash screen » <=> écran d’accueil ou écran d’attente c’est ici
Pour réaliser un compteur temporel, temps d’attente, utilisez la fonction CountDownTimer qui permet d’exécuter une tâche au bout de x millisecondes tout en s’interrompant toutes les y millisencondes :
  new CountDownTimer(30000, 1000) {  //-- x,y
    public void onTick(long millisUntilFinished) {  
      mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);  
    }  
    public void onFinish() {  
      mTextField.setText("done!");  
    }  
  }.start();  
1°) Définition de la tâche asynchrone :
Créer une classe (par exemple MyTask) possédant une à quatre des méthodes suivantes :
  • onPreExecute() : Initialisation d’une fenêtre progress dialog et gestion éventuelle du click d’annulation
  • doInBackground() : Prévoir

if (isCancelled())
break; //– On sort de la tâche

  • onProgressUpdate()
  • onPostExecute()

Les déclarations de variables s’effectuant en début de classe (avant les méthodes) pour que les variables puissent être utilisées dans chaque méthode.

2°) Appel de la tâche asynchrone :
MyTask objMyTask = new MyTask();
Pour la lancer :  objMyTask.execute();
3°) Règles d’utilisation :
  •  L’instanciation de la tâche asynchrone doit être dans le thread principal de l’application (l’UI thread),
  • .execute doit être invoqué dans l’UI thread,
  • Ne jamais appeler manuellement  objMyTask.onPreExecute(), objMyTask.doInBackground(), objMyTask.onProgressUpdate(),  objMyTask.onPostExecute,
  • l’AsyncTask ne doit être appelée qu’une fois dans l’application (une exception sera levée sinon).

4°) Exemple :

a) Progress bar simple avec % :

Placer dans l’activité : 

 //-- Progress Bar InitDb  
 private ProgressDialog progress;  
 private int jumpTime = 1;  
 //--  

Et créer une fonction

 public void Initialisation(){  
   final int totalProgress = drawables.length; //100 ou taille de la liste...  
   //-- Si la table des icônes n'est pas initialisée  
   progress=new ProgressDialog(this);  
   progress.setMessage(getResources().getString(R.string.lib_initdb));  
   progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
   // progress.setIndeterminate(true); //-- Pour roue  
   progress.setMax(totalProgress);  
   progress.setProgress(0);  
   progress.show();  
   new Thread(new Runnable() {  
       @Override  
       public void run() {  
         for (Field f : drawables) {  
           try {  
             String sNomIco;  
             int nIdIco;  
             sNomIco = f.getName();  
             nIdIco = getDrawable(MainActivity.this, sNomIco);  
             //  
             jumpTime=jumpTime+1;  
             //-- Traitement  
             //-------------  
           } catch (Exception e) {  
             e.printStackTrace();  
           }  
           progress.setProgress(jumpTime);  
         }  
         progress.dismiss();  
       }  
     }  
     ).start();  
   }  
 }  

b) Avec activité :

 import android.app.Activity;  
 import android.app.AlertDialog;  
 import android.app.Dialog;  
 import android.app.ProgressDialog;  
 import android.content.DialogInterface;  
 import android.os.AsyncTask;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.view.Window;  
 import android.widget.Button;  
 import android.widget.ProgressBar;  
 import android.widget.TextView;  
 import android.widget.Toast;  
 public class MainActivity extends Activity {  
      Button btnStart;  
      MyTask objMyTask;  
      private static final int SLEEP_TIME=((60*1000)/100);  
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.main);  
           btnStart = (Button) findViewById(R.id.btnstart);  
           btnStart.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                     objMyTask = new MyTask();  
                     objMyTask.execute();  
                }  
           });  
      }  
      class MyTask extends AsyncTask<Void, Integer, Void> {  
           Dialog dialog;  
           ProgressBar progressBar;  
           TextView tvLoading,tvPer;  
           Button btnCancel;  
     ProgressDialog progress;   
           @Override  
           protected void onPreExecute() {  
                super.onPreExecute();  
                /*  
                dialog = new Dialog(MainActivity.this);  
                dialog.setCancelable(false);  
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);  
                dialog.setContentView(R.layout.progressdialog);  
                progressBar = (ProgressBar) dialog.findViewById(R.id.progressBar1);  
                tvLoading = (TextView) dialog.findViewById(R.id.tv1);  
                tvPer = (TextView) dialog.findViewById(R.id.tvper);                 
                btnCancel = (Button) dialog.findViewById(R.id.btncancel);  
                btnCancel.setOnClickListener(new OnClickListener() {  
                     @Override  
                     public void onClick(View v) {  
                          objMyTask.cancel(true);  
                 Toast.makeText(MainActivity.this,"Interruption du traitement !",Toast.LENGTH_LONG).show();  
                          dialog.dismiss();  
                     }  
                });  
                dialog.show();  
           */       
                 //--Déclarations   
          progress = new ProgressDialog(MainActivity.this);    
           // On ajoute un message à notre progress dialog   
           progress.setMessage("Chargement des musiques en cours...");   
           progress.setTitle("Initialisation");   
           progress.show();   
           }  
           @Override  
           protected Void doInBackground(Void... params) {  
                for (int i = 1; i <10; i++) {  
                     if (isCancelled()) {  
                          break;  
                     } else {  
                          System.out.println(i);  
                     //     publishProgress(i);  
                          try {  
                               Thread.sleep(SLEEP_TIME);  
                          } catch (InterruptedException e) {  
                               e.printStackTrace();  
                          }  
                     }  
                }  
                return null;  
           }  
           @Override  
           protected void onProgressUpdate(Integer... values) {  
                super.onProgressUpdate(values);  
                /*  
                progressBar.setProgress(values[0]);  
                tvLoading.setText("Loading... " + values[0] + " %");  
                tvPer.setText(values[0]+" %");  
                */  
           }  
           @Override  
           protected void onPostExecute(Void result) {  
                super.onPostExecute(result);  
                //dialog.dismiss();  
       //-- Fin de traitement des données   
       progress.dismiss();   
                AlertDialog alert = new AlertDialog.Builder(MainActivity.this)  
                          .create();  
                alert.setTitle("Completed!!!");  
                alert.setMessage("Your Task is Completed SuccessFully!!!");  
                alert.setButton("Dismiss", new DialogInterface.OnClickListener() {  
                     @Override  
                     public void onClick(DialogInterface dialog, int which) {  
                          dialog.dismiss();  
                     }  
                });  
                alert.show();  
           }  
      }  
 }  

Laisser un commentaire

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur la façon dont les données de vos commentaires sont traitées.

Articles récents
Commentaires récents
fatima dans Bienvenue !
AdminDroid dans Bienvenue !
fatima dans Bienvenue !
Archives
Catégories