Android:Toast在使用线程时显示较晚

时间:2015-02-27 04:41:28

标签: android multithreading toast

所以我将代码组合在一起下载ImageView中显示的图像,并且当用户点击下载按钮时我正试图设置Toast,这样他们就知道发生了什么事情。问题是Toast会在几秒钟后出现,而不是在他们点击下载按钮时出现。我已经尝试用runOnUiThread方法包装它,同时它也在新线程中,但问题仍然存在。有人能指出我正确的方向来解决这个问题吗?该课程的代码如下。

public static final String EXTRA_IMAGE_URL = "extra_image_url";

private ImageView mImage;
private ImageView mDownloadImage;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView( R.layout.activity_social_image_download );

    if( getIntent() == null || getIntent().getExtras() == null || !getIntent().getExtras().containsKey( EXTRA_IMAGE_URL ) ) {
        finish();
    }

    String imageUrl = getIntent().getExtras().getString( EXTRA_IMAGE_URL, "" );

    if( TextUtils.isEmpty( imageUrl ) ) {
        finish();
    }

    mImage = (ImageView) findViewById( R.id.image );
    mDownloadImage = (ImageView) findViewById( R.id.download_button );

    mDownloadImage.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveImage();
        }
    });
    Picasso.with( this ).load( imageUrl ).into( mImage );
}

private void saveImage() {
    Toast.makeText( this, "Downloading Image", Toast.LENGTH_SHORT ).show();
    new Thread(new Runnable() {
        @Override
        public void run() {
            File file1 = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/" + getString( R.string.app_name ) );
            if( !file1.isDirectory() )
                file1.mkdir();

            File file = new File( file1.getPath() + "/" + (new Date()).getTime() + ".png");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ((BitmapDrawable) mImage.getDrawable() ).getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
            try {
                file.createNewFile();
                FileOutputStream fout = new FileOutputStream( file );
                if( fout != null ) {
                    fout.write( out.toByteArray() );
                    fout.flush();
                    fout.close();
                }

                MediaScannerConnection.scanFile(getApplicationContext(), new String[] { file.getAbsolutePath() }, null, new MediaScannerConnection.OnScanCompletedListener() {

                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                    }
                });


            } catch( IOException e ) {}
        }
    }).start();
}

2 个答案:

答案 0 :(得分:0)

也许如果您使用AsyncTask,您可以处理此问题。因为onPreExecute()可以为您提供所需的祝酒词。

private class SaveImageTask extends AsyncTask<Void, Void, Void> {

     @Override   
     protected void onPreExecute (){
        Toast.makeText( this, "Downloading Image", Toast.LENGTH_SHORT ).show();
     }

     @Override   
     protected void doInBackground(URL... urls) {
        File file1 = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/" + getString( R.string.app_name ) );
            if( !file1.isDirectory() )
                file1.mkdir();

            File file = new File( file1.getPath() + "/" + (new Date()).getTime() + ".png");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ((BitmapDrawable) mImage.getDrawable() ).getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
            try {
                file.createNewFile();
                FileOutputStream fout = new FileOutputStream( file );
                if( fout != null ) {
                    fout.write( out.toByteArray() );
                    fout.flush();
                    fout.close();
                }
            }catch(Exception e){
                    //Error handling.
            }

     }


     @Override   
     protected void onPostExecute(Long result) {

                MediaScannerConnection.scanFile(getApplicationContext(), new String[] { file.getAbsolutePath() }, null, new MediaScannerConnection.OnScanCompletedListener() {

                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                    }
                });
     }
   }
 }

答案 1 :(得分:0)

原来这个问题与线程和吐司无关。在创建活动和按钮能够响应点击之间有几秒钟的延迟。如果活动已开始,我等待按下下载按钮直到四秒钟后,一切都按预期工作。试着找出导致UI线程暂时挂在这样一个基本Activity中的内容。即使删除Picasso并且位图只是作为意图中的额外内容传递,问题仍然存在。