0

我筋疲力尽。我整天都在做这个。在我的应用程序中,我有 100 个 ImageView,但出现 java.outofmemory 错误,所以我决定解码并调整文件大小,但我无法管理它工作。有人可以看一下代码并向我提出任何建议吗?

MainActivity 代码: public class MainActivity extends Activity implements OnClickListener {

ImageView display;
int toPhone;
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    System.gc();
    context = this;
    toPhone = R.drawable.wal1;
    display = (ImageView) findViewById(R.id.WPdisplay);
    ImageView image1 = (ImageView) findViewById(R.id.WPimg1);
    ImageView image2 = (ImageView) findViewById(R.id.WPimg2);
    ImageView image3 = (ImageView) findViewById(R.id.WPimg3);
    ImageView image4 = (ImageView) findViewById(R.id.WPimg4);
    ImageView image5 = (ImageView) findViewById(R.id.WPimg5);
    Button setWall = (Button) findViewById(R.id.BsetWall);
    image1.setOnClickListener(this);
    image2.setOnClickListener(this);
    image3.setOnClickListener(this);
    image4.setOnClickListener(this);
    image5.setOnClickListener(this);
    setWall.setOnClickListener(this);
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public Bitmap decodeAndResizeFile(int resID) {
     try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;

我认为在下一行我有一个问题,因为它说The value of the local variable bmp is not used

            Bitmap bmp= BitmapFactory.decodeResource(context.getResources(), resID, o);
           // BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // The new size we want to scale to
            final int REQUIRED_SIZE = 70;

            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeResource(context.getResources(), resID, o2);

     } finally {

        }
    }

@Override
public void onClick(View v) {
    Bitmap bmpp;
    switch (v.getId()){
    case R.id.WPimg1:
         display.setImageResource(R.drawable.wal1);
         toPhone = R.drawable.wal1;

在下一行中,我正在尝试对其进行解码(并且我正在为每个图像执行此操作)

         bmpp = decodeAndResizeFile(toPhone);
         //Bitmap bmpp = decodeAndResizeFile(file);
         break;
    case R.id.WPimg2:
         display.setImageResource(R.drawable.wal2);
         toPhone = R.drawable.wal2;  
         bmpp = decodeAndResizeFile(toPhone);
        display.setImageBitmap(bmpp);
         break;
    case R.id.WPimg3:
         display.setImageResource(R.drawable.wal3);
         toPhone = R.drawable.wal3;
         bmpp = decodeAndResizeFile(toPhone);
         break;
    case R.id.WPimg4:
         display.setImageResource(R.drawable.wal4);
         toPhone = R.drawable.wal4;
         bmpp = decodeAndResizeFile(toPhone);
         break;
    case R.id.WPimg5:
         display.setImageResource(R.drawable.wal5);
         toPhone = R.drawable.wal5;
         bmpp = decodeAndResizeFile(toPhone);
         break;
    case R.id.BsetWall:
         try{
             WallpaperManager.getInstance(getApplicationContext()).setResource(toPhone);
             Toast.makeText(getApplicationContext(), "Wallpaper was set!", Toast.LENGTH_SHORT).show();
         } catch(IOException e) {
             e.printStackTrace();
             Toast.makeText(getApplicationContext(), "No privileges!", Toast.LENGTH_SHORT).show();
         }
         break;
    }
    }
    }

这是我的 Logcat

--- decoder->decode returned false
Shutting down VM
threadid=1: thread exiting with uncaught exception (group=0xb3adbba8)
FATAL EXCEPTION: main
Process: app.technozed.testwall, PID: 1250
java.lang.RuntimeException: Unable to start activity ComponentInfo{app.technozed.testwall/app.technozed.testwall.MainActivity}: android.view.InflateException: Binary XML file line #304: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #304: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:620)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
at android.app.Activity.setContentView(Activity.java:1929)
at app.technozed.testwall.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
... 11 more
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:594)
... 26 more
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:587)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:422)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:840)
at android.content.res.Resources.loadDrawable(Resources.java:2110)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.widget.ImageView.<init>(ImageView.java:119)
... 29 more
4

1 回答 1

1

如果在 decodeAndResizeFile() 中出现警告“未使用局部变量 bmp 的值”,则可以删除“Bitmap bmp =”部分并将其保留为:

BitmapFactory.decodeResource(context.getResources(), resID, o);

这是因为此调用使用 o.inJustDecodeBounds = true。在这种情况下,仅在对象“o”中返回尺寸并返回空位图(因此没有必要存储它)。

在您的 switch 语句中,将每种情况更改为如下所示:

case R.id.WPimg1:
    toPhone = R.drawable.wal1;
    bmpp = decodeAndResizeFile(toPhone);
    display.setImageBitmap(bmpp);
    break;

因此,在这里,您将资源解码为按比例缩小的位图,然后将该位图分配给 ImageView。您不想或不需要这样做:

display.setImageResource(R.drawable.wal1);

...因为您冒着 OutOfMemoryException 的风险,并且您继续使用缩放位图设置“显示”。进行了这些更改后,您的代码对我有用。我可以看到壁纸预览图像,然后设置壁纸(不要忘记清单中的 SET_WALLPAPER 权限)。

但是,这并不能解释您的 logcat,这似乎是 onCreate() 膨胀 R.layout.activity_main 的问题。在您的 logcat 快结束时,它再次显示 OutOfMemoryError。如果我将一个大的 jpg 分配给 XML 中的 ImageView(OOM 结果和布局因此不能膨胀),我可以重新创建此错误。在 XML 中分配时,您不能“即时”缩小可绘制对象,因此创建物理上更小的可绘制对象以在 XML 中使用。

编辑:

当您单击图像时,“显示”会获得一个新的位图,而旧的位图有资格进行 GC。这是一种立即释放旧内存使用的方法,而无需等待 GC 启动:

将它从 onClick() 移到一个类变量中:

Bitmap bmpp;  //Reference to the same bitmap that 'display' is using

然后在 onClick() 中:

Bitmap old_bm = null;  //Reference to hold the old bitmap
switch (v.getId()){
case R.id.WPimg1:
    old_bm = bmpp;  //Set to the bitmap currently being used by 'display'
    toPhone = R.drawable.wal1;
    bmpp = decodeAndResizeFile(toPhone);   //'display' now has a new bitmap
    display.setImageBitmap(bmpp);
    if (old_bm != null)
    {
        old_bm.recycle();  //Recyle the old bitmap
        old_bm = null;     //Clear the reference to allow GC to clean up fully
    }
    break;
于 2014-01-29T11:15:06.180 回答