使用onCreate准备好后切换到活动

时间:2016-12-24 06:45:08

标签: java android android-activity loading

我有两项活动,一项是以onCreate开始另一项活动。儿童活动在"1,2,3.000"中有大量工作要做。第一个活动仅用于加载。当我开始儿童活动时,我在完成加载后等待黑屏。

如何等待第一个活动并在完成创建后切换到第二个活动(某些监听器或回调?)

1 个答案:

答案 0 :(得分:0)

你必须使用AsyncTask。

试用此代码

public class MainActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // call your long task from here
        doWork();
    }

    // write this method in your First Activity
    private void doWork()
    {

        new AsyncTask<Void, Void, String>()
        {

            ProgressDialog progressDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Loading...");
                progressDialog.show();
            }

            @Override
            protected String doInBackground(Void... params) {

                // do your long task here

                // And return your result to the onPostExecute method.
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);

                // after finishing your task dismis your dialog.
                progressDialog.dismiss();

                // And go to your next Activity.

                Intent intent = new Intent(MainActivity.this, NextActivity.class);
                startActivity(intent);
            }
        }.execute();

    }
}