为什么带有300张图像的应用程序停止工作?

时间:2018-10-27 10:13:59

标签: android listview android-activity imageview out-of-memory

我创建了一个包含300张图像的应用。在应用程序启动时,它可以顺畅运行,没有问题。但是当我启动加载图像的listactivity时,我的应用程序停止响应。救救我。

这是我的 MainActivity 代码。 我将图像zip文件从资产文件夹复制到内部存储中,然后从内部存储中提取图像,然后在mainactivity的gridview中显示它们。

private void createDirs()
{
    File zipFileLoc = new File(storagePath, zipLoc);
    File unzipFileLoc = new File(storagePath, unzipLoc);
    File aksFileLoc = new File(storagePath, aks);
    if(zipFileLoc.exists() && unzipFileLoc.exists() && aksFileLoc.exists()){
        getFromStorage();
    }else{
        zipFileLoc.mkdirs();
        unzipFileLoc.mkdirs();
        aksFileLoc.mkdirs();

        copyAssets();
        unzip();

        getFromStorage();
    }
}

private void copyAssets()
{
    AssetManager assets = getAssets();
    String[] files = null;
    try{
        files = assets.list("");
    }catch(Exception e){
        Toast.makeText(this, "Failed to load images, please restart app", Toast.LENGTH_LONG).show();
    }
    for(String fileName : files){
        InputStream in = null;
        OutputStream out = null;
        try{
            in = assets.open(fileName);
            File zipOutFile = new File(storagePath + zipLoc, fileName);
            out =new FileOutputStream(zipOutFile);
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        }catch(Exception e){
            Toast.makeText(this, "Failed to load images, please restart app", Toast.LENGTH_LONG).show();
        }
    }
}

private void copyFile(InputStream in, OutputStream out) throws IOException
{
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
}

private void unzip()
{
    pd = new ProgressDialog(this);
    pd.setMessage("Please wait...");
    pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    pd.setCancelable(false);
    pd.show();

    new UnZipTask().execute(storagePath + zipLoc + "/AAGRIKOLISTATUS.zip", storagePath + aks);
}

private class UnZipTask extends AsyncTask<String, Void, Boolean>
{
    @SuppressWarnings("rawtypes")
    @Override
    protected Boolean doInBackground(String[] p1)
    {
        String filePath = p1[0];
        String destinationPath = p1[1];

        File archive = new File(filePath);
        try{
            ZipFile zf = new ZipFile(archive);
            for(Enumeration e = zf.entries(); e.hasMoreElements();){
                ZipEntry entry = (ZipEntry) e.nextElement();
                unzipEntry(zf, entry, destinationPath);
            }
            UnzipUtil d = new UnzipUtil(storagePath + zipLoc + "/AAGRIKOLISTATUS.zip", storagePath + aks);
            d.unzip();
        }catch(Exception e){
            return false;
        }

        return true;
    }

    @Override
    protected void onPostExecute(Boolean result)
    {
        pd.dismiss();
    }

    private void unzipEntry(ZipFile zf, ZipEntry entry, String destinationPath) throws IOException
    {
        if(entry.isDirectory()){
            createDir(new File(destinationPath, entry.getName()));
            return;
        }

        File outputFile = new File(destinationPath, entry.getName());
        if(!outputFile.getParentFile().exists()){
            createDir(outputFile.getParentFile());
        }

        BufferedInputStream inputs = new BufferedInputStream(zf.getInputStream(entry));
        BufferedOutputStream outputs = new BufferedOutputStream(new FileOutputStream(outputFile));

        try{

        }finally{
            outputs.flush();
            outputs.close();
            inputs.close();
        }
    }

    private void createDir(File file)
    {
        if(file.exists()){
            return;
        }

        if(!file.mkdirs()){
            throw new RuntimeException("Cannot create file " + file);
        }
    }
}

private void getFromStorage()
{
    File file = new File(storagePath, aks);
    if(file.isDirectory()){
        listfile= file.listFiles();
        for(int i = 0; i < listfile.length; i++){
            f.add(listfile[i].getAbsolutePath());
        }
    }

    ad = new ImageAdapter(this);
    gv.setAdapter(ad);
}
public class ImageAdapter extends BaseAdapter
{
    Context context;

    public ImageAdapter(Context cxt)
    {
        this.context = cxt;
    }

    @Override
    public int getCount()
    {
        return f.size();
    }

    @Override
    public Object getItem(int p1)
    {
        return p1;
    }

    @Override
    public long getItemId(int p1)
    {
        return p1;
    }

    @Override
    public View getView(int p1, View p2, ViewGroup p3)
    {
        ImageView iv = new ImageView(context);
        Bitmap bm = BitmapFactory.decodeFile(f.get(p1));
        iv.setImageBitmap(bm);
        iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        iv.setLayoutParams(new GridView.LayoutParams(240, 240));

        return iv;
    }
}

这是我的main.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp"
android:gravity="center"
android:background="#00ff85">

<GridView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/aagrikolistatusphotoGridView"
    android:layout_above="@+id/aagrikolistatusphotocomgoogleandroidgmsadsAdView"
    android:columnWidth="90dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:horizontalSpacing="5dp"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:verticalSpacing="5dp"/>

1 个答案:

答案 0 :(得分:0)

即使您在后台线程上解压缩图像,但在主线程上加载它们也会导致UI崩溃。解决方案是使用Glide或Picasso在后台线程上加载图像。请阅读Google文档: https://developer.android.com/topic/performance/graphics/load-bitmap#java
并尝试使用其中之一:
滑行: https://github.com/bumptech/glide
毕加索: http://square.github.io/picasso/
那应该有助于解决您的问题