Function in Background - Android

1

Hello, I need to put an animation on the screen, it can only be visible for 10 seconds, after that time it disappears, and if the user clicks a specific button the animation comes back. Can someone help me? I can not solve it.

Thank you!

    
asked by anonymous 25.05.2016 / 21:27

1 answer

1

Possible solution would be to use the Package class java.util : Timer . With this class it is possible to schedule tasks or that a certain task is executed at certain time intervals or until then schedule the specified task to run after the specified delay. I use the schedule in one of your implementations that receives 2 parameters: TimerTask and delay .

In your XML :

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Mostrar ProgressBar"
    android:id="@+id/button"
/>

<ProgressBar
    android:id="@+id/progressBar"
    android:indeterminate="true"
    android:visibility="gone"
    ...
/>

...

Here in XML I added the attribute android:visibility="gone" to View ProgressBar to keep "hidden" element!

In your Activity:

//recupera o Button e o ProgressBar do XML
Button bt = (Button) findViewById(R.id.button);
ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.progressBar);

//Evento de click do botão
bt.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         //Quando clica no botão torna visível o ProgressBar
         mProgressBar.setVisibility(View.VISIBLE);


         Timer timer  = new Timer();
         timer.schedule(new TimerTask() {
             @Override
             public void run() {

                 runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       //Depois que passa os 10s "esconde" o ProgressBar
                       mProgressBar.setVisibility(View.GONE);
                    }
                 });
             }
          },10000);//Aqui o delay é um long em milisegundos
      }
});

Internally in the schedule method I still use the runOnUiThread of Activity to manipulate (hide) View (ProgressBar) , otherwise it would generate a Exception because it is manipulating the UI in the background so with this method it moves the action to Main Thread .

    
28.05.2016 / 00:24