线程没有在后台运行

时间:2011-07-29 21:22:25

标签: android multithreading

我从菜单调用此函数并调用upload(item)函数来传递所选优先级的索引。

public void showPriorityDialog()
{
    final CharSequence[] priority = {"1 Hour", "12 Hours", "24 Hours", "Cancel"};

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Select Priority");
    builder.setItems(priority, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            if(item != 3)
                upload(item);
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

但是,每当我调用上传函数时,线程都不会在后台运行,并且操作系统认为应用程序由于执行超时而没有响应。

public void upload(int priority)
{    
        final int _priority = priority;
        uploadThread = new Thread()
        {
            @Override
            public void run()
            {
                try
                {
                    super.run();                    

                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            try
                            {
                                //ftp commands...
                            }
                            catch (Exception e)
                            {
                                Toast.makeText(getApplicationContext(), e.toString() , Toast.LENGTH_SHORT).show();
                            }


                        }
                    });

                }
                catch (Exception e)
                {
                    Toast.makeText(getApplicationContext(), e.toString() , Toast.LENGTH_SHORT).show();
                }
            }                   
        };
        uploadThread.start();

}
我做错了什么? TIA

1 个答案:

答案 0 :(得分:1)

执行mHandler.post()时,整个Runnable在UI线程上执行,后台线程就会退出。要修复,请在发布到处理程序之前执行FTP。然后执行mHandler.post()以显示Toast。请注意,您catch还需要通过帖子显示Toast。