Turin Turin - 1 year ago 96
Android Question

Start generic Activity and wait for AsyncTask to complete

Starting from an Activity X, when some event happens, Activity A is started (is a progress bar), and this activity A starts an AsyncTask that, when finished, closes Activity A and goes back to Activity X. This event cant be executed in a lot of different activities, and the code executed by the AsyncTask can be different (and usually must access a lot of variables from Activity X).

So I want to have only one Activity A, but make it execute different pieces of code inside the AsyncTask. The problem here is that I cannot construct the Activity A with a custom constructor (passing for example the runnable that will be executed in the AsyncTask).

I have tried to pass the code as Parcelable from the Activity X, but it forces me to write a lot of useless and repeated Parcelable-related code every time I want to call the Activity A.

Is there any trick to do this? I am not using Java 8, so lambdas are not an option.

Thank you in advance.

Answer Source

When using a progress bar to prompt the user to wait while you do something, try to launch a dialog containing the progress bar instead of another Activity. This way you'll be able to do (what I think) you want to do. Then, close the dialog when task finishes, and you won't need to move insane amounts of data back and forth between Activities.

For example:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:indeterminate="true" />

Use a custom style for your dialog if required adding to styles.xml something like

<style name="myCustomDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:windowBackground">@color/my_color</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">false</item>

Then, in your Activity X, call the dialog

Dialog d = new Dialog(this, R.style.myCustomDialog);
AsyncTask task.execute(); //Execute your task

When the task ends, don't forget to close the dialog, or design your layout to give users control (if possible) over the task to cancel it and close the dialog if required.

Hope it helps.