如何在oncreate完成后发布http?

时间:2015-03-20 08:17:07

标签: android android-activity http-post

我有一个MainActivity,其中包含onCreate方法。在该课程中,它应加载layout并将数据发布到server。只要活动开始,它就会变为空白,只会转到下一个活动SignUpActivity。我需要的是MainActivity布局首先显示,然后execute显示httpPost


以下是我的代码

public class MainActivity extends Activity {
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    progressBar = (ProgressBar) findViewById(R.id.progress_bar);
    context = this;

    new MainAsyncTask().execute(""); // where should i put this code? here??
}

   private class MainAsyncTask extends AsyncTask<Object, Integer, String> {
    @Override
    protected String doInBackground(Object... params) {
        String result = null;
        String url = "some url";
        Log.i("Post", "Post HTTP");

        HttpPostHelper.postData(url); // method to post the http. i made myself
        intent = new Intent(context, SignUpActivity.class);
        startActivity(intent);
        return result;
    }
}

}

我只是希望在设备上完全显示布局后执行MainAsyncTask.execute("")

解决

我移动new MainAsyncTask().execute("");并将其添加到此处,它运行正常:

@Override
protected void onStart() {
  super.onStart();
  new MainAsyncTask().execute("");
}

4 个答案:

答案 0 :(得分:0)

呼叫AsynTask似乎没问题,但您不应该在doInBackground()

中调用您的意图

onPostExecute()方法

中调用它
 protected void onPostExecute(String result){
intent = new Intent(context, SignUpActivity.class);
        startActivity(intent);

}

答案 1 :(得分:0)

尝试onStart()活动方法

答案 2 :(得分:0)

您可以在Thread.sleep之前尝试startActivity,以便为主要版面添加一些时间来加载和显示。您还应拨打startActivity中的onPostExecute

答案 3 :(得分:0)

根据你的代码,它应该是这样的。照顾@ doinbackground(),因为这不正确。

public class MainActivity extends Activity {
    private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        context = this;

    new MainAsyncTask().execute(""); // where should i put this code? here??
}

   private class MainAsyncTask extends AsyncTask<Object, Integer, String> {



protected void onPreExecute( ){

//start Progressbar
    progressBar.show();

}


    @Override
    protected String doInBackground(Object... params) {
        String result = null;
        String url = "some url";
        Log.i("Post", "Post HTTP");

        HttpPostHelper.postData(url); // method to post the http. i made myself

        return result;
    }



 protected void onPostExecute(String result){

//stuff u want in main thread
    progressBar.cancell();
    intent = new Intent(context, SignUpActivity.class);
            startActivity(intent);

    }
}

}