简体   繁体   中英

How can I run my function in a thread in android?

I have a function that dynamically creates all my user interface.

What can I do to show a dialog progress while my function is executing, and then dismiss the dialog when my function has finished the user interface?

This is an example of my code:

Sorry, I'm new to android, it is hard for me to understand some code... I will write my code here...

I have this function:

 public void principal() {
        //CODE TO CREATE ALL THE USER INTERFACE DYNAMICALLY
    }

and I have the asyncTask like this:

public class EjecutarTarea extends AsyncTask<Void, Void, Void>
{
    protected void onPreExecute() {
        dialog = new ProgressDialog(StadioNenaActivity.this);
        dialog.setMessage("Cargando..");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }


    protected Void doInBackground(Void... unused) {


        Principal();
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... unused) {

    }

    @Override
    protected void onPostExecute(Void unused) {

        dialog.dismiss();
    }
  }

When I execute the asynctask in the onCreate, it crashes:

new EjecutarTarea().execute();

Use an AsyncTask . It gives a fantastic and easy way to load stuff in the background and them paste views in the main thread.

Here is an example of my AsyncTask:

private class LoadingTask extends AsyncTask<Void, Integer, Void> {
        private ProgressBar mProg;
        private TextView mLoadingText;

        @Override protected void onPreExecute() {
            mProg = (ProgressBar)findViewById(R.id.launcherbar_loadprogress);
            mProg.setTouchDelegate(null);
            mProg.setClickable(false);
            mProg.setLongClickable(false);
            mProg.setOnTouchListener(null);
            mProg.setMax(100);

            mLoadingText = (TextView) findViewById(R.id.launcheractivity_loadingwhat);
        }

        @Override protected Void doInBackground(Void... voids) {
            try { Thread.sleep(1000); } catch (InterruptedException e) { }

            setProgressAndSleep(R.string.loading_log, 29, 250);
            LOG.setContext(LauncherActivity.this);
            LOG.setDebug(true);

            setProgressAndSleep(R.string.loading_database, 43, 250);
            AppionDatabase.setContext(LauncherActivity.this);

            setProgressAndSleep(R.string.loading_sensors, 57, 250);
            Sensor.init(LauncherActivity.this);

            setProgressAndSleep(R.string.loading_jobs, 71, 250);
            Job.init(LauncherActivity.this);

            setProgressAndSleep(R.string.loading_workbenches, 86, 250);
            WorkbenchState.init(LauncherActivity.this);

            setProgressAndSleep(R.string.loading_application_state, 100, 250);
            ApplicationState.setContext(LauncherActivity.this);
            startService(new Intent(LauncherActivity.this, BluetoothConnectionService.class));

            return null;
        }

        @Override public void onProgressUpdate(Integer... prog) {
            mLoadingText.setText(prog[0]);
            mProg.setProgress(prog[1]);
        }

        @Override public void onPostExecute(Void voids) {
            startActivity(new Intent(LauncherActivity.this, HomescreenActivity.class));
        }

        private void setProgressAndSleep(int text, int progress, int duration) {
            try {
                publishProgress(new Integer[] {text, progress});
                Thread.sleep(duration);
            } catch (InterruptedException e) {
                LOG.e(TAG, "Failed to sleep thread while loading Application Contexts!", e);
            }
        }
    }

Edit NOTE I recommend not keeping the setProgressAndSleep(int, int int) method. I only use it cause it loads too fast and I really wanted the loading bar. :-P

All changes in Android UI will makes in UI Thread . To run your function in UI thread you need to use mathos runOnUIThread() from activity http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable )

Hope it help you!

Your best shot is, probably, to use ViewSwitcher to have temporary view with progress bar while you construct other view. Do operations that take time in doInBackground() of AsyncTask but actual operations on UI such as flipping the view must be done in postExecute() or via runOnUIThread() . Progress updates may be done in onProgressUpdate()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM