android上的线程问题。请帮忙

时间:2013-05-24 03:48:40

标签: android multithreading progressdialog

我有button。在onclick事件中,想要运行一个progressDialog,然后在加载progressDialog时运行AsyncTask

我的代码:

方法OnCreate

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

principal_layout = (RelativeLayout) findViewById(R.id.principal_layout);
text_search = (TextView) findViewById(R.id.textView1);
search_button = (Button) findViewById(R.id.button1);
input_song = (EditText) findViewById(R.id.editText1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);

search_button.setOnClickListener(new OnClickListener() {

@Override
    public void onClick(View v) {

        runOnUiThread(new Runnable() {
                public void run() {
                    pd = ProgressDialog.show(MainActivity.this, "Working..", "Loading, please wait..", true, false);
                }
            });

        handler.sendEmptyMessage(1);

    }});
}

方法处理程序(var Handler)

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        if(msg.what == 1){
            try {
                songs = new AsyncTasks().new GetSong(MainActivity.this).execute("mySong","1").get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            catch (ExecutionException e) {
                e.printStackTrace();
            }
            sendEmptyMessage(0);
        }
        else if(msg.what == 0){
            Toast.makeText(MainActivity.this, "Finished process", Toast.LENGTH_SHORT).show();

            if(pd != null && pd.isShowing()){
                pd.dismiss();
            }
        }
    }

};

代码不会产生任何错误,但接下来是:

当我点击按钮时,程序执行以下行:

songs = new AsyncTasks()。new GetSong(MainActivity.this).execute(“mySong”,“1”)。get();

,一旦它完成运行,那么最近有progressDialog显示。我的希望是它显示了点击按钮的确切时刻(没有延迟)。

1 个答案:

答案 0 :(得分:0)

你可以这么简单明了:

Handler h = new Handler();
button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        pd = ProgressDialog.show(MainActivity.this, "Working..", "Loading, please wait..", true, false);
        new Thread(new Runnable() {
            public void run() {
                //Loading code
                h.post(new Runnable() {
                    public void run() {
                        pd.dismiss();
                    }
                });
            }
        }).start();
    }
});