Taking Screenshot and Sharing - Android

Viewed 28

Trying to Take Screenshot, and Share that image. Tried bunch of codes, stack, youtube. dont know where is the problem in my code. Taking screenshot as unknown format. Tried png,jpeg. still remains same.

Screen while share intent

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_screen);
    
    View rootView  = getWindow().getDecorView().getRootView();
    Button bat = findViewById(R.id.btsharee);
    bat.setOnClickListener(
            view ->
             shareImage(store(getScreenShot(rootView),"sos.jpeg")));
}

method for screenshot and storing

public static Bitmap getScreenShot(View view) {
    view.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
    view.setDrawingCacheEnabled(false);
    return bitmap;
}
public static File store(Bitmap bm, String fileName){
    final String dirPath = Environment
            .getExternalStorageDirectory().getAbsolutePath() +"/Screenshots";

    File dir = new File(dirPath);
    if(!dir.exists()){
        boolean mkdir = dir.mkdir();
    }
    File file = new File(dirPath, fileName);
    try {
        FileOutputStream fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.JPEG,100, fOut);
        fOut.flush();
        fOut.close();
        return file;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return dir;
}
private void shareImage(File file){
    Uri uri;
    if (Build.VERSION.SDK_INT < 24) {
        uri = Uri.fromFile(file);
        uri = Uri.parse(file.getPath());
    } else {
        uri = Uri.parse(file.getPath());
    }
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*"); //also tried image/jpeg 
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
    intent.putExtra(android.content.Intent.EXTRA_TEXT, "Msg:" );
    try {
        startActivity(Intent.createChooser(intent, "Share Screenshot"));
    } catch (ActivityNotFoundException e) {
        Toast.makeText(context, "No App Available", Toast.LENGTH_SHORT).show();
    }
}

I checked storage permission, but storage permission have no problem.

Can anyone help me out..?

0 Answers
Related