share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(SingleProduct.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
Log.e("MainActivity ", "P granted");
bmpUri = getLocalBitmapUri(imageView);
} else {
ActivityCompat.requestPermissions(SingleProduct.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
} else {
Log.e("MainActivity", "Lower Than MarshMallow");
bmpUri = getLocalBitmapUri(imageView);
}
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
Toast.makeText(SingleProduct.this, "Sharing Failed !!", Toast.LENGTH_SHORT).show();
}
}
});
public Uri getLocalBitmapUri(ImageView imageView) {
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
Uri bmpUri = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
//for oreo add below code in manifest under application tag
<provider
android:name=".utility.GenericFileProvider"
android:authorities="${applicationId}.your package
name.utility.GenericFileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
create class that extends FileProvider
public class MyFileProvider extends FileProvider {
}
for oreo add this code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
bmpUri = FileProvider.getUriForFile(this,
this.getApplicationContext().getPackageName() +
".your package name.GenericFileProvider", file);
} else {
bmpUri = Uri.fromFile(file);
}
finally add provider_paths.xml in res/xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
それで全部です