0

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

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

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

班级:

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();

}

}
4

1 回答 1

1

您需要在输入流上调用 close 方法。理想情况下,这应该在 finally 块中,这样即使有异常也会被调用。为此,请将您的 InputStream 声明移到 try 之外:

InputStream is = null;

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

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

 finally{
      if(is != null){
          try{
            is.close();
          }catch(Exception e){}
      }
    }
于 2013-11-09T18:34:39.500 回答