等待Google将照片请求放在AsyncTask中

问题描述 投票:0回答:1

我试图了解如何将Asynctasks与其他请求一起使用,因此我可以在AsyncTask内使用Google地点获取照片。

我得到的是,在处理请求时,Asynctask在我得到照片之前完成,因此它为null。

我相信问题在于,在发出请求时,任务正在完成,并继续执行其余的代码。

我的AsyncTask类的构建如下:

private class AsyncPhotoBuilder extends AsyncTask<Integer, Integer, Bitmap[][]>{

    ProgressBar pb;
    int status = 0;

    private void setProgressBar(ProgressBar progressBar){
        this.pb = progressBar;
    }

    @Override
    protected void onPostExecute(Bitmap[][] bitmaps) {
        super.onPostExecute(bitmaps);
        Log.d("debug", "onpost");
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        pb.setProgress(values[0]);
    }

    @Override
    protected Bitmap[][] doInBackground(Integer... integers) {
        try{
            int xSize = 4, ySize = 4;
            SharedPreferences prefs = getSharedPreferences(PHOTO_PREF, MODE_PRIVATE);
            String meta = prefs.getString("meta", "empty");
            if(!meta.equals("empty")){
                int loc = meta.indexOf(photoref_loc);
                String holder = meta.substring(loc+photoref_loc.length());
                PhotoMetadata temp = PhotoMetadata.builder(holder.substring(0, holder.length()-1)).build();


                FetchPhotoRequest photoRequest = FetchPhotoRequest.builder(temp)
                        .setMaxWidth(800) // Optional.
                        .setMaxHeight(800) // Optional.
                        .build();
                //Starts a request for a photo
                placesClient.fetchPhoto(photoRequest).addOnSuccessListener((fetchPhotoResponse) -> {
                    Photo_Bitmap.set(fetchPhotoResponse.getBitmap());
                    int width, height;

                    width = Photo_Bitmap.get().getWidth()/xSize;
                    height = Photo_Bitmap.get().getHeight()/ySize;
                    //Cuts photo into a 4x4
                    for(int i = 0; i < xSize; i++){
                        for(int j = 0; j < ySize; j++){
                            PuzzleList[i][j] = Bitmap.createBitmap(Photo_Bitmap.get(), i*width, j*height, width, height);
                            status++;
                            publishProgress(status);

                        }
                    }
                    //Once finished cutting photo raise flag.
                    ready_flag = true;
                    Log.d("debug", "finish");
                }).addOnFailureListener((exception) -> {
                    if (exception instanceof ApiException) {
                        ApiException apiException = (ApiException) exception;
                        int statusCode = apiException.getStatusCode();
                        // Handle error with given status code.
                        Log.e("debug", "Photo not found: " + exception.getMessage());
                    }
                });
            }
        }
        catch (Exception e){
            Log.d("Exception", "Error in splitting photo: " + e);
        }
        return PuzzleList;
    }
}

根据我的理解,onPostExecute发生在请求完成之前。我尝试了一些方法:

1使用Asynctasks的get()函数

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /*
    Code...
    */

    asyncPhotoBuilder = new AsyncPhotoBuilder();
    asyncPhotoBuilder.setProgressBar(progressBar);
    asyncPhotoBuilder.execute(5000);
    try{
        PuzzleList = asyncPhotoBuilder.get(5000, TimeUnit.MILLISECONDS);
    }
    catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    }

    /*
    Code...
    */
}

但是我认为在请求之前完成任务遇到了相同的问题。


android google-maps android-asynctask google-places-api
1个回答
0
投票

我在写这篇文章的时候,确实解决了我的问题。

我在请求内设置了一个标志(ready_flag),该标志在请求完成后就被提出。

使用运行程序检查任务是否完成以及标志是否升起。

不确定这是否是我本可以处理的最佳方法。

    public Runnable Start = new Runnable() {
        @Override
        public void run() {
            if(asyncPhotoBuilder.getStatus() == AsyncTask.Status.FINISHED && ready_flag){
                Init_start();
            }
            hand.postDelayed(this, 0);
        }
    };

[如果有更好的方法可以做到,请爱学习。

谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.