执行异步请求时出现OutOfMemoryException

时间:2012-05-23 16:05:26

标签: android facebook asynchronous

我正在尝试将自己的照片/视频上传到脸谱,并且在尝试上传超过2张照片,视频或任何组合时我遇到了内存问题。我的设备是HTC Desire:

Publishvideo

public void publishVideo( Bundle kParameters) {
final String kDataPath = kParameters.getString( "video");
kParameters.remove( "picture");
kParameters.remove( "video");

byte[] yData = null;
InputStream kInputStream = null;

try {
    kInputStream = new FileInputStream( kDataPath);
    yData = readBytes( kInputStream);
    kParameters.putString( "token",
                           ms_kFacebookClient.getAccessToken());
    kParameters.putByteArray( "video", yData);
    AsyncFacebookRunner kAsyncRunner = new AsyncFacebookRunner( m_kFacebookClient);
    kAsyncRunner.request( "me/videos",
                             kParameters,
                             "POST",
                             new RequestListener(),
                             null);
} catch ( FileNotFoundException e) {
    e.printStackTrace();
    FacebookX.ms_bIsUploading = false;
} catch ( IOException e) {
    e.printStackTrace();
    FacebookX.ms_bIsUploading = false;
} catch ( OutOfMemoryError e){
    e.printStackTrace();
    FacebookX.ms_bIsUploading = false;
}
 }

图片:

public void publishLocalPicture( Bundle kParameters) {
byte[] yData = null;

final String kDataPath = kParameters.getString( "picture");
kParameters.remove( "picture");
kParameters.remove( "video");
kParameters.remove( "filename");

try {
    Bitmap kBitmap = BitmapFactory.decodeFile( kDataPath);
    ByteArrayOutputStream kByteArrayOutputStream = new ByteArrayOutputStream();
    kBitmap.compress( Bitmap.CompressFormat.JPEG,
                      100,
                      kByteArrayOutputStream);
    yData = kByteArrayOutputStream.toByteArray();

    kParameters.putString( "token",
                           ms_kFacebookClient.getAccessToken());
    kParameters.putByteArray( "picture", yData);

    AsyncFacebookRunner kAsyncRunner = new AsyncFacebookRunner( m_kFacebookClient);
    kAsyncRunner.request( "me/photos",
                             kParameters,
                             "POST",
                             new RequestListener(),
                             null);

} catch ( OutOfMemoryError e) {
    e.printStackTrace();
    FacebookX.ms_bIsUploading = false;
}
}

的ReadBytes:

public byte[] readBytes( InputStream kInputStream) throws IOException {
ByteArrayOutputStream kByteBuffer = new ByteArrayOutputStream();

int iBufferSize = 1024;
byte[] yBuffer = new byte[iBufferSize];

int iLenght = 0;
while ( ( iLenght = kInputStream.read( yBuffer) ) != -1) {
    kByteBuffer.write( yBuffer, 0, iLenght);
}

return kByteBuffer.toByteArray();
}

1 个答案:

答案 0 :(得分:0)

显然,当方法完成时,垃圾收集器没有清理资源,所以我在方法结束之前手动完成。

yBuffer = null;
kBitmap.recycle();
kByteArrayOutputStream.close();
kInputStream.close();

永远不要相信垃圾收集器。