为整个活动拍照,有时会使应用程序崩溃

时间:2018-12-28 07:45:19

标签: java android

当我按下“共享”按钮时,我的应用会截取所有活动(甚至没有可见部分)的屏幕截图,并通过意图进行共享。我发现有时它会起作用,有时却不会。我不明白这个问题。 那是我的代码:

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

1 个答案:

答案 0 :(得分:0)

您的位图在此处为空。请调试位图的值,然后交叉检查它是否为null。或者,您可以使用下面的代码截取屏幕截图,将此函数置于常规方法中,并将视图传递给它。

fun takeScreenshot(context: View?, activity: Activity) {
val now = Date()
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now)
try {
    val mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg"
    // create bitmap screen capture
    context?.isDrawingCacheEnabled = true
    val bitmap = Bitmap.createBitmap(context?.drawingCache)
    context?.isDrawingCacheEnabled = false
    val imageFile = File(mPath)
    val outputStream = FileOutputStream(imageFile)
    val values = ContentValues()
    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
    values.put(MediaStore.MediaColumns.DATA, mPath)
    activity.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
    val quality = 100
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
    outputStream.flush()
    outputStream.close()
    Toast.makeText(activity, activity.getString(R.string.saved_to_gallery), Toast.LENGTH_SHORT).show()
} catch (e: Throwable) {
    e.printStackTrace()
}