开发者

Android - ProgressDialogs and Threads

I have a ProgressDialog that I couldn't get to display for love nor money. A bit of research suggested I needed to put it in a thread.

So example

public void Updat开发者_StackOverflowe(final int ScheduleId, final Context context) {
    final Handler progressHandler = new Handler() {
        public void handleMessage(Message msg) {
            x.dismiss();
        }
    };        

        x = ProgressDialog.show(context, "Scheduling...", "Calculating and Storing Dates", true, false);        
    new Thread() {
        public void run() {
            // Do Nothing
            boolean bResult = UpdateHistory(ScheduleId, context);
            Log.i("HERE","Finished Here?");
            if (bResult) {  
                progressHandler.sendEmptyMessage(0);
            }
        }
    }.start();
}

But all that seems to happen for me, is that the spinner just disappears off the screen and the activity finishes, while UpdateHistory continues to run in the background.

If I move the call to UpdateHistory below the .start() (outside of the thread), I don't get a progress spinner displayed at all.

What exactly is it that Im missing?

All this code is in an Activity.

What can you recommend, most websites appear to talk about threads and I've tried doing them every which way you can, and as I say, I either get the the thread run in the background and the spinner displayed for a second, or I get no spinner at all while the function runs in the foreground.

Thanks Simon


The preferred way is with an AsyncTask, but you should also be able to do it with a Thread, something like this:

public class MyActivity extends Activity {
    ...
    private static final HANDLER_MESSAGE_SUCCESS = 0;
    private ProgressDialog x;
    ...
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
            case HANDLER_MESSAGE_SUCCESS:
                x.dismiss();
            default:
                Log.w("Handler","handleMessage / Message type not recognised / msg.what = "+String.valueOf(msg.what));
            }
        }
    };
    private void backgroundProcess(){
        x = ProgressDialog.show(MyActivity.this, "Scheduling...", "Calculating and Storing Dates", true, false);
        Thread backgroundThread = new Thread() {
            @Override
            public void run() {
                boolean bResult = UpdateHistory(ScheduleId, MyActivity.this);
                Log.i("HERE","Finished Here?");
                if (bResult) {  
                    Message msg = Message.obtain();
                    msg.what = HANDLER_MESSAGE_SUCCESS;
                    handler.sendMessage(msg);
                }
            }
        };
        backgroundThread.start();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜