代码之家  ›  专栏  ›  技术社区  ›  juniano

使用AsyncTask加载图像时的行为不一致

  •  0
  • juniano  · 技术社区  · 15 年前

    应用程序的功能非常简单。它加载两个RSS提要,在每个RSS提要上,它包含两个具有标题、图像和链接的项。然后它下载图像,保存到本地文件夹并显示它们。所以两个RSS源和4个图片下载。

    我使用AsyncTask来执行此操作。因此,调用两个AsyncTasks对象来加载两个RSS源,并调用4个AsyncTasks来加载4个图像。当它试图下载图像时会出现问题。在第一次运行中,它运行良好。但如果我不断地重新加载它们,有时AsyncTask什么都不做。有时它无法读取inputstream…非常奇怪。

    是否有我缺少的使用AsyncTask的规则?

    下面是我的代码片段。

    public class TunesAppsWidgetProvider extends AppWidgetProvider {
    
    private Intent taService = null;
    private static boolean widgetEnabled = false;
    
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        taService = new Intent(context, UpdateService.class);
        context.startService(taService);
    }
    
    public static class UpdateService extends Service {
    
    
        @Override
        public void onStart(Intent intent, int startId) {
            Log.d(Constants.TAG, "Service: onStart()");
            Context context = getApplicationContext();
            mViews = new RemoteViews(context.getPackageName(), R.layout.tunesappswidget);
    
            thisWidget = new ComponentName(this, TunesAppsWidgetProvider.class);
            manager = AppWidgetManager.getInstance(this);
    
            buildFeedUpdate();
    
            this.stopSelf();
            Log.d(Constants.TAG, "Stop Service");
        }
    
        public void buildFeedUpdate() {
            Log.d(Constants.TAG, "buildFeedUpdate");
            Context context = getApplicationContext();
    
            feedParser_0 = new FeedParser(context, Constants.FEED_ID_0);
            feedParser_1 = new FeedParser(context, Constants.FEED_ID_1);
    
            feedTask_0 = new LoadFeedTask();
            feedTask_0.execute(
                    new LoadFeedTask.Payload(
                            feedParser_0,
                            UpdateService.this
                    )
            );
    
            feedTask_1 = new LoadFeedTask();
            feedTask_1.execute(
                    new LoadFeedTask.Payload(
                            feedParser_1,
                            UpdateService.this
                    )
            );
        }
    
        public void buildCoverUpdate(byte feedID, List<Message> feedRSS, String operator) {
            Context context = getApplicationContext();
    
            Log.d(Constants.TAG, "buildCoverUpdate: " + feedID);
            try {
                switch(feedID) {
                    case Constants.FEED_ID_0:
                            coverImage_0 = new CoverImage(context, feedRSS.get(Constants.ITEM_IDX_0).getImageLink(), Constants.SLOT_0);
    
                coverImageTask_0 = new LoadCoverImageTask();
                            coverImageTask_0.execute(
                                new LoadCoverImageTask.Payload(
                                        coverImage_0,
                                        UpdateService.this
                                )
                            );
    
                            coverImage_1 = new CoverImage(context, feedRSS.get(Constants.ITEM_IDX_1).getImageLink(), Constants.SLOT_1);
    
                            coverImageTask_1 = new LoadCoverImageTask();
                                coverImageTask_1.execute(
                                    new LoadCoverImageTask.Payload(
                                        coverImage_1,
                                        UpdateService.this
                                    )
                            );
                        break;
    
                    case Constants.FEED_ID_1:
                            coverImage_2 = new CoverImage(context, feedRSS.get(Constants.ITEM_IDX_0).getImageLink(), Constants.SLOT_2, operator);
                        coverImageTask_2 = new LoadCoverImageTask();
                            coverImageTask_2.execute(
                                    new LoadCoverImageTask.Payload(
                                            coverImage_2,
                                            UpdateService.this
                                    )
                            );
    
                            coverImage_3 = new CoverImage(context, feedRSS.get(Constants.ITEM_IDX_1).getImageLink(), Constants.SLOT_3, operator);
                            bm_3 = coverImage_3.getDefaultCoverImage();
                                coverImageTask_3 = new LoadCoverImageTask();
                                coverImageTask_3.execute(
                                    new LoadCoverImageTask.Payload(
                                        coverImage_3,
                                        UpdateService.this
                                    )
                            );
                        break;
    
                    default:
                        break;
                }
            }
            catch(Exception e) {
                Log.d(Constants.TAG, "buildCoverUpdate: " + e.toString());
            }
        }
    

    }

    下面的代码用于加载图像。有时,即使调用了“execute”,也不会调用这个doinbackground。有时它会卡在“bitmap bitmap=bitmapfactory.decodestream(in)”上,永远不会转义。

        protected LoadCoverImageTask.Payload doInBackground(LoadCoverImageTask.Payload... param) {
        HttpURLConnection httpConn = null;
        InputStream in;
        File imageFile;
        FileOutputStream fos;
        int slotIdx = param[0].coverImage.getSlotIndex();
        System.setProperty("http.keepAlive", "false");
    
        try{
            URL fileURL = new URL(param[0].coverImage.getFileURL());
            httpConn = (HttpURLConnection) fileURL.openConnection();
            Log.d(Constants.TAG , "openConn: Slot " + slotIdx);
    
            httpConn.setConnectTimeout(10000);
    
            if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                Log.d(Constants.TAG , "200OK: Slot " + slotIdx + ": " + fileURL.toString());
    
                in = httpConn.getInputStream();
                imageFile = new File(param[0].coverImage.getFullFilePath());
                fos = new FileOutputStream(imageFile);
    
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(in);
                    Log.d(Constants.TAG , "200OK: Slot " + slotIdx + " decodeStream(in);");
                    if(bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos) == true) {
                        fos.flush();
                        fos.close();
                        in.close();
                        Log.d(Constants.TAG , "200OK-decodeOK: Slot " + slotIdx);
                        param[0].result = Constants.TRUE;
                    }
                    else {
                        fos.flush();
                        fos.close();
                        in.close();
                        Log.d(Constants.TAG , "200OK-decodeFail: Slot " + slotIdx);
                        param[0].result = Constants.FALSE;
                    }
                }
                catch(NullPointerException e) {
                    Log.d(Constants.TAG , "Slot " + slotIdx + ":" + e.toString());
                    param[0].result = Constants.RETRY;
                }
            }
            else {
                Log.d(Constants.TAG , "Slot " + slotIdx + ":" + httpConn.getResponseCode());
                param[0].result = Constants.FALSE;
            }
    
        } catch(SocketTimeoutException e) {
            Log.d(Constants.TAG , "Time Out: " + slotIdx + ":" + e.toString());
        } catch(Exception e) {
            Log.d(Constants.TAG , "Slot " + slotIdx + ":" + e.toString());
            param[0].result = Constants.FALSE;
        }
        finally {
            if(httpConn != null) httpConn.disconnect();
            Log.d(Constants.TAG , "Slot " + slotIdx + ":httpConn.disconnect");
        }
        return param[0];
    }
    

    我在这上面呆了几天。请帮助…

    1 回复  |  直到 15 年前
        1
  •  1
  •   Marcel Dancak    15 年前

    也许问题不在您的代码中。BitmapFactory.decodestream中有一个bug,如果使用来自HTTP连接的inputstream,它有时无法很好地加载图像。

    看 http://code.google.com/p/android/issues/detail?id=6066 更多信息

    对于我来说,简单的解决方案是将整个内容数据下载到缓冲区,然后 使用BitmapFactory.DecodeBytearray方法:

    InputStream is = httpCon.getInputStream();
    byte [] content = inputStreamToByteArray2(is);
    image = BitmapFactory.decodeByteArray(content, 0, content.length);
    
    
    public static final byte[] inputStreamToByteArray(InputStream is) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        int result = bis.read();
        while(result !=-1) {
            byte b = (byte)result;
            buf.write(b);
            result = bis.read();
        }
        return buf.toByteArray();
    }
    

    或者如果不想读取1字节:

    public static final byte[] inputStreamToByteArray(InputStream is) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int result = bis.read(buffer);
        while(result > 0) {
            buf.write(buffer, 0, result);
            result = bis.read(buffer);
        }
        return buf.toByteArray();
    }
    
    推荐文章