确保在执行异步任务后启动活动

时间:2016-03-19 14:33:14

标签: android

我想确保在执行异步任务后我的活动开始。截至目前,它已在异步任务在后台完成

之前启动

这是调用新活动的地方。在调用新活动之前,我调用了PagerAsyncTask。我想确保只有在成功完成PagerAsyncTask之后才调用新活动。

 protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        new PagerAsyncTask().execute();
            sharedPreferences = getSharedPreferences(Constants.MY_PREFS, 0);
            SharedPreferences.Editor editor = getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE).edit();
            editor.putBoolean("hasadd", false);
            editor.commit();
            Log.e("hi", "dsscdds");
            startActivity(new Intent(SplashScreenActivity.this, NavigationActivity.class));

PagerAsyncTask

   class PagerAsyncTask extends AsyncTask<String,Void,String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            StringBuilder sb=null;
            BufferedReader reader=null;
            String serverResponse=null;
            try {

                URL url = new URL("https://enigmatic-woodland-35608.herokuapp.com/pager.json");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                connection.connect();
                int statusCode = connection.getResponseCode();
                //Log.e("statusCode", "" + statusCode);
                if (statusCode == 200) {
                    sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                }

                connection.disconnect();
                if (sb!=null)
                    serverResponse=sb.toString();
                Log.e("haha", serverResponse);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return serverResponse;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //All your UI operation can be performed here
            //Response string can be converted to JSONObject/JSONArray like
            try {
//String mr[] = new String[5];
                JSONObject response=new JSONObject(s);
                Iterator<?> keys = response.keys();
                int i=0;

                while( keys.hasNext() ) {

                    String key = (String)keys.next();
                    Log.e("hi",key);
                    Log.e("hey",response.getString(key));
//                    mr[i]=response.getString(key);
//                    Log.e("e=",mr[i]);
                    i++;

                }
                Log.e("I", String.valueOf(i));
                Iterator<?> keys1 = response.keys();
                mr = new String[i];
                int k=0;
                while ( keys1.hasNext() )
                {
                    String key = (String)keys1.next();
                    mr[k++]=response.getString(key);
                    Log.e("fdvfd",mr[k-1]);
                }
                for (int j=0;j<mr.length;j++)
                {
                    Log.e("dsd",mr[j]);
                }
                isComplete=true;
                setMr(mr);
                setSet(1);
                new RestaurantFragment().setmResources(mr);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

2 个答案:

答案 0 :(得分:1)

您需要将startActivity移动到AsyncTask的postExecute。

没有startActivity的onCreate:

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    new PagerAsyncTask().execute();
    sharedPreferences = getSharedPreferences(Constants.MY_PREFS, 0);
    SharedPreferences.Editor editor = getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE).edit();
    editor.putBoolean("hasadd", false);
    editor.commit();
    Log.e("hi", "dsscdds");

PagerAsyncTask onPostExecute:

@Override
protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //All your UI operation can be performed here
        //Response string can be converted to JSONObject/JSONArray like
        try {
            JSONObject response=new JSONObject(s);
            Iterator<?> keys = response.keys();
            int i=0;

            while( keys.hasNext() ) {

                String key = (String)keys.next();
                Log.e("hi",key);
                Log.e("hey",response.getString(key));|
                i++;

            }
            Log.e("I", String.valueOf(i));
            Iterator<?> keys1 = response.keys();
            mr = new String[i];
            int k=0;
            while ( keys1.hasNext() )
            {
                String key = (String)keys1.next();
                mr[k++]=response.getString(key);
                Log.e("fdvfd",mr[k-1]);
            }
            for (int j=0;j<mr.length;j++)
            {
                Log.e("dsd",mr[j]);
            }
            isComplete=true;
            setMr(mr);
            setSet(1);
            new RestaurantFragment().setmResources(mr);
            startActivity(new Intent(SplashScreenActivity.this, NavigationActivity.class));
        } catch (JSONException e) {
            e.printStackTrace();
        }

此外,代码新的RestaurantFragment()。setmResources(mr);可能什么都不做,因为你没有将片段附加到任何地方

答案 1 :(得分:1)

有几种方法可以做到这一点

1)在onPostExecute()

中使用startActivity

2)将活动引用传递给Async任务,并从onPostExecute调用活动中的某些函数,如show here

3)将函数回调传递给AsyncTask,如图here所示。虽然这对您的任务来说不必要地复杂化