【发布时间】:2018-12-28 15:55:36
【问题描述】:
当我按下“分享”按钮时,我的应用会截取所有活动(甚至没有可见部分)并通过意图分享。我发现有时它有效,有时则无效。我无法理解这个问题。 这是我的代码:
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkPermission();
}
});
// Inside the checkPermission method, if the user allow them:
Bitmap bitmapScreen = takeScreenshot();
saveBitmap(bitmapScreen);
}
public Bitmap takeScreenshot() {
rechoose.setVisibility(View.GONE);
share.setVisibility(View.GONE);
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
rootView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
rootView.layout(0, 0, rootView.getMeasuredWidth(), rootView.getMeasuredHeight());
rootView.buildDrawingCache(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
UUID uuid = UUID.randomUUID();
String randomUUIDString = "/" + uuid.toString() + ".png";
rechoose.setVisibility(View.VISIBLE);
share.setVisibility(View.VISIBLE);
imagePath = new File(Environment.getExternalStorageDirectory() + randomUUIDString);
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.v("errorFileNotFound", e.getMessage(), e);
} catch (IOException e) {
Log.v("Exception", e.getMessage(), e);
}
Uri uri = FileProvider.getUriForFile(RateActivity.this, BuildConfig.APPLICATION_ID + ".provider", imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
我收到了这个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.my.name.myapp.RateActivity.saveBitmap(RateActivity.java:211)
第 211 行是:
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
这有点奇怪,因为有时有效,有时无效。 在我的活动中,我从我的画廊加载了一张图片。使用我从图库中挑选的一些图像,该应用程序会截取屏幕截图,而其他图像则不会。 显然,如果应用程序没有截取屏幕截图,那么我在 bitmap.compress 上得到一个 nullPointerException。但我不明白为什么它不截图。 如果我这样写 takeScreenshot() 方法,它随时都可以工作:
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
【问题讨论】:
-
有时如果您没有获得正确的路径,那么您将不会获得导致问题的位图。必须确保在保存到存储时获得正确的路径。