Java 无法解析getApplicationContext()
我正在尝试使用一种方法从布局生成位图,并将位图保存到内存中的文件中。但是,getApplicationContext()未解析 下面是该方法的代码Java 无法解析getApplicationContext(),java,android,Java,Android,我正在尝试使用一种方法从布局生成位图,并将位图保存到内存中的文件中。但是,getApplicationContext()未解析 下面是该方法的代码 private void generateAndSaveBitmap(View layout) { //Generate bitmap layout.setDrawingCacheEnabled(true); layout.buildDrawingCache(); Bitmap imageToS
private void generateAndSaveBitmap(View layout) {
//Generate bitmap
layout.setDrawingCacheEnabled(true);
layout.buildDrawingCache();
Bitmap imageToSave = layout.getDrawingCache();
//Create a file and path
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File fileName = new File(directory, "sharableImage.jpg");
if (fileName.exists())
fileName.delete();
//Compress and save bitmap under the mentioned fileName
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileName);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// return directory.getAbsolutePath();
}
使用StackOverFlow代码中的一些帮助来生成此方法。即使在阅读了getApplicationContext()
上的相关查询之后,我也无法找到问题所在。任何帮助都将不胜感激
编辑:忘了提到,generateAndSaveBitmap(视图布局)
方法是在一个单独的类中定义的
关于试试看
ContextWrapper cw = new ContextWrapper(getActivity());
如果它是一个片段。步骤1:删除ContextWrapper cw=newcontextwrapper(getApplicationContext())代码>,因为您不需要它
步骤2:替换cw.getDir(“imageDir”,Context.MODE_PRIVATE)代码>带有layout.getContext().getDir(“imageDir”,Context.MODE\u PRIVATE)代码>
另外,请将此磁盘I/O移动到后台线程。您是否尝试过:
File dir = getApplicationContext().getDir(Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE);
现在,从图像处理到将文件写入目录,所有工作都应该离线完成。如果可能,将其封装在AsyncTask中,并在其中移动generateAndSaveBitmap()
方法。getApplicationContext()
是上下文上的一个方法。使用buildDrawingCache()时,类是否以某种直接或间接的方式扩展上下文;使用后还需要销毁it@user3802077谢谢你的观点。添加到代码中已遇到getActivity()。但是没有。它不是碎片。感谢您留下关于后台线程的信息。忘了吧。