Background function - Android

Asked

Viewed 370 times

1

Hello, I need to place 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’m not getting it right.

Thank you very much!

  • You want the progress bar indeterminate turns in background? And after 10s that gives the show it disappear (keep running in background)? And when you click a specific button it reappears?

  • I want that after I press a certain button the bar Progress appears and disappear after 10 seconds.

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 for a given task to be executed in certain time intervals or until schedule the specified task for execution after the specified delay. I use the function schedule in one of its implementations that receives 2 parameters: TimerTask and delay.

In his 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" in View ProgressBar to maintain "hidden" the element!

In his 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 method schedule still use the method runOnUiThread of Activity to manipulate (hide) the View (ProgressBar), otherwise it would generate a Exception because it is manipulating the UI in the background then with this method moves the action to Main Thread.

  • Thank you so much for the answer! Helped me :D

  • You’re welcome! We’re here to help and really be helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.