我想创建通用的AsyncTask,它可用于保存图像的所有活动

时间:2017-05-11 20:24:33

标签: java android android-asynctask

我创建了一个ImageLoading类,用于下载数据并将数据保存到本地存储。我也是从多个活动中调用它。保存后,我需要更新创建asyncTask实例的类的集合。我不想在任务中使用if语句来处理这个问题,我不想将此任务继承到其他活动。请建议我如何做到这一点。我在这里分享我的代码。

public class LoadImageTask extends AsyncTask<Void, Void, Bitmap> {

    private String url;
    private ImageView imageView;
    private long ID;
    private Context context;
    private SQLiteHandler sqLiteHandler;
    private String imageType;
    private int position;

    public LoadImageTask(String url, ImageView imageView, long ID, Context context, String imageType, int position) {
        this.url = url;
        this.imageView = imageView;
        this.ID = ID;
        this.context = context;
        this.imageType = imageType;
        this.position = position;
        sqLiteHandler = new SQLiteHandler(context);
    }

    String getRandomString(int length)
    {
        String data = "";
        Random rand = new Random();

        for (int i = 1 ; i <= length ; i++) {
            int n = rand.nextInt(26) + 97;
            data += String.valueOf((char)n);
        }

        return data;
    }

    private File getOutputMediaFile(){
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Android/data/"
                + context.getPackageName()
                + "/Files");

        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                return null;
            }
        }

        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmssSSS").format(new Date());
        timeStamp = String.format("%s_%s", timeStamp, getRandomString(10));
        File mediaFile;
        String mImageName="Image_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
        return mediaFile;
    }

    private void storeImage(Bitmap image) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            Log.d("Error:","Error creating media file, check storage permissions: ");
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
            ImageDownload imageDownload = new ImageDownload(ID,pictureFile.getAbsolutePath());
            if(imageType.equals(Constants.ImageType.PROFILE)) {
                sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.PROFILE);
            }
            else if(imageType.equals(Constants.ImageType.BANNER)) {
                sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.BANNER);
            }
            else if(imageType.equals(Constants.ImageType.SUBJECT)) {
                if(sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.SUBJECT)){
                    ((MainActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;
                    //((MainActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;
                    //((MessageList) context).messageDataItems.get(position).SubjectImage = imageDownload.ImagePath;
                }
            }

        } catch (FileNotFoundException e) {
            Log.d("Error:", "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d("Error:", "Error accessing file: " + e.getMessage());
        }
    }

    @Override
    protected Bitmap doInBackground(Void... params) {
        try {
            URL urlConnection = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlConnection
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        Drawable d = new BitmapDrawable(imageView.getResources(), result);
        imageView.setBackground(d);
        storeImage(result);
        //imageView.setImageBitmap(result);
    }

}

1 个答案:

答案 0 :(得分:0)

只需这样做:

((AppCompatActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;