简体   繁体   中英

thread not running in background

i am calling this function from the menu and calls the upload(item) function to pass the index of the selected priority.

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();
}

however, whenever i call the upload function, the thread doesn't run in background, and the OS thinks that the app is not responding due to executing timeout.

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();

}

am i doing something wrong? TIA

When you do mHandler.post() , your entire Runnable executes on UI thread and your background thread just exits. To fix, do FTP before posting to handler. Then do mHandler.post() to have Toast appear. Note that you catch also need to display Toast via post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM