关闭输入流以停止资源泄漏

时间:2013-11-09 18:25:36

标签: android inputstream

我最近遇到了“资源是在附加堆栈跟踪中获取但从未发布过”的问题

我已经读过你需要在使用后关闭连接。我找不到任何可以帮助我的问题所以我正在编写自己的问题。

在用于防止这种情况发生之后,我如何关闭输入流?

类:

public class SetWallpaperAsync extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog pDialog;
String image_url;
URL mImageUrl;
String myFileUrl;
Bitmap bmImg = null;

public SetWallpaperAsync(Context context) {
this.context = context;
} 

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub

super.onPreExecute();

pDialog = new ProgressDialog(context);
pDialog.setMessage("Setting Wallpaper...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub

try {

    mImageUrl = new URL(args[0]);


    HttpURLConnection conn = (HttpURLConnection) mImageUrl
            .openConnection();
    conn.setDoInput(true);
    conn.connect();
    InputStream is = conn.getInputStream();



    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Config.RGB_565;
    Bitmap bmImag = BitmapFactory.decodeStream(is, null, options);





} catch (IOException e) {
    e.printStackTrace();
}

return null;
}

@Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
WallpaperManager wpm = WallpaperManager.getInstance(context);
try {
    wpm.setBitmap(bmImg);
} catch (IOException e) {

    // TODO Auto-generated catch block
    e.printStackTrace();
}
pDialog.dismiss();

}

}

1 个答案:

答案 0 :(得分:1)

您需要在输入流上调用close方法。理想情况下,这应该在finally块中,因此即使存在异常也会调用它。要实现此目的,请将您的InputStream声明移到try:

之外
InputStream is = null;

然后你可以在try块中执行此操作:     is = conn.getInputStream();

然后,在你的catch块之后,包含一个finally:

 finally{
      if(is != null){
          try{
            is.close();
          }catch(Exception e){}
      }
    }