0
在我的應用程序中,我想在後臺執行位圖轉換,因爲我面臨內存泄漏問題。我知道,可以使用Async Task完成,但不知道如何執行此操作。下面我張貼我的代碼。在後臺執行位圖轉換
package com.android.album3;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class Album3Activity extends Activity
{
File [] mediaFiles;
File imageDir;
static GridView gridView;
ImageAdapter adapter;
Intent in;
String name = null;
ArrayList<Bitmap> bmpArray = new ArrayList<Bitmap>();
ArrayList<String> fileName = new ArrayList<String>();
public static final String TAG = "Album3Activity";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
imageDir = new File(Environment.getExternalStorageDirectory().toString()+
"/diplomat");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
if(imageDir.exists())
{
setContentView(R.layout.grid);
mediaFiles = imageDir.listFiles();
//Log.d("Length of images",""+mediaFiles.length);
for(File file : mediaFiles)
{
bmpArray.add(convertToBitmap(file));
fileName.add(readFileName(file));
Log.d(TAG + "bmpArray Size", ""+bmpArray.size());
Log.d(TAG, "call to convertToBitmap");
}//for
adapter = new ImageAdapter(this, bmpArray, fileName);
gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3)
{
in = new Intent(getApplicationContext(), FullScreen.class);
in.putExtra("id", position);
startActivity(in);
}//onItemClick
});
}//if
else
{
setContentView(R.layout.no_media);
//Toast.makeText(Album3Activity.this, "No files available", Toast.LENGTH_SHORT).show();
}//else
}//onCreate
public static Bitmap convertToBitmap(File file)
{
URL url = null;
try
{
url = file.toURL();
}//try
catch (MalformedURLException e1)
{
Log.d(TAG, e1.toString());
}//catch
Bitmap bmp = null;
try
{
bmp = BitmapFactory.decodeStream(url.openStream());
//bmp.recycle();
}//try
catch(Exception e)
{
Log.d(TAG, "Exception: "+e.toString());
}//catch
return bmp;
}//convertToBitmap
public String readFileName(File file)
{
String name = file.getName();
return name;
}//readFileName
}//class