I need to take a screenshot of Activity (without the title bar, and the user should NOT see that a screenshot has actually been taken) and then share it via an action menu button "share". I have already tried some solutions, but they didn't work for me. Any ideas?
This is how I captured the screen and shared it.
First, get root view from current activity:
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Second, capture the root view:
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
Third, store the Bitmap into the SDCard:
public static void store(Bitmap bm, String fileName){
final static String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
At last, share the screenshot of current Activity:
private void shareImage(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No App Available", Toast.LENGTH_SHORT).show();
}
}
I hope you will be inspired by my code.
UPDATE:
Add below permissions into your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Because it creates and accesses files in external storage.
UPDATE:
Starting from Android 7.0 Nougat sharing file links are forbiden. To deal with this you have to implement FileProvider and share "content://" uri not "file://" uri.
Here is a good description how to do it.
create share button with click on listener
share = (Button)findViewById(R.id.share);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
shareIt();
}
});
Add two methods
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
Share screen shot. sharing implementation here
private void shareIt() {
Uri uri = Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "In Tweecher, My highest score with screen shot";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Tweecher score");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
This Method Doesn't Need to Store and Retrieve Screenshot for Sharing Again.
On just Method Call you will Able to Share Screenshot.
private Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
private void share(Bitmap bitmap){
String pathofBmp=
MediaStore.Images.Media.insertImage(ctx.getContentResolver(),
bitmap,"title", null);
Uri uri = Uri.parse(pathofBmp);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Star App");
shareIntent.putExtra(Intent.EXTRA_TEXT, "");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
ctx.startActivity(Intent.createChooser(shareIntent, "hello hello"));
}
Called this Method like this
share(screenShot(view));
By using this Direct Share Screenshot without having READ & WRITE Permission
You can the below code to get the bitmap for the view you are seeing on screen You can specify which view to create bitmap.
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
I couldn't get Silent Knight's answer to work to work until I added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
to my AndroidManifest.xml.
You can take screenshot of any portion of your view.You just need the reference of the layout of which you want the screenshot. for example in your case you want the screen shot of your activity. let assume that your activity root layout is Linear Layout .
// find the reference of the layout which screenshot is required
LinearLayout LL = (LinearLayout) findViewById(R.id.yourlayout);
Bitmap screenshot = getscreenshot(LL);
//use this method to get the bitmap
private Bitmap getscreenshot(View view) {
View v = view;
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
return bitmap;
}
for taking screenshot
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
for saving screenshot
private void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() + "/scrnshot.png"); ////File imagePath
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
and for sharing
private void shareIt() {
Uri uri = Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "My highest score with screen shot";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Catch score");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
and simply in the onclick you can call these methods
shareScoreCatch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
shareIt();
}
});
as of 2021 here is complete answer you would only copy past this code and it should work fine with you, also it uses all the new API including permission launchers, and android q way of saving images
I will be adding one more functionality which is saving inside folder inside Picture folder like this
/Pictures/MyAppName/photos.png
also this code is supporting android < 10 as well as the newer one.
i am making a screen shoot and saving it to desk to get uri of the image, to be able to share it later.
first, permission launcher is required on android < 10
val requestStoragePermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
var saveImageFlag = true
permissions.entries.forEach {
saveImageFlag = it.value
}
if (saveImageFlag) {
shareScreenShootResult()
} else {
showMessage(getString(R.string.cant_share_ScreenShoot))
}
}
val permissionListener: () -> Boolean = {
if (ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
) {
true
} else {
requestStoragePermissionLauncher.launch(
arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
)
false
}
}
then the next method gives the image name and set the directory and then share the image
private fun shareScreenShootResult() {
val dateFormatter by lazy {
SimpleDateFormat(
"yyyy.MM.dd 'at' HH:mm:ss z", Locale.getDefault()
)
}
val filename = "${getString(R.string.my_ScreenShoot)}${dateFormatter.format(Date())}.png"
val ScreenShootFolderPath = File.separator + requireContext().getAppName()
val uri = binding.rootLayout.makeScreenShot()
.saveScreenShot(requireContext(), filename, ScreenShootFolderPath, permissionListener)
?: return
dispatchShareImageIntent(uri)
}
private fun dispatchShareImageIntent(screenShotUri: Uri) {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/png"
intent.putExtra(Intent.EXTRA_STREAM, screenShotUri)
startActivity(Intent.createChooser(intent, "Share"))
}
getAppName is an extention funtion, you can add it anywhere in your project then call it on context, do not forget to import it.
fun Context.getAppName(): String {
var appName: String = ""
val applicationInfo = applicationInfo
val stringId = applicationInfo.labelRes
appName = if (stringId == 0) {
applicationInfo.nonLocalizedLabel.toString()
} else {
getString(stringId)
}
return appName
}
this method makeScreenShot is extension function on the View
you better add all extension functions in different file.
fun View.makeScreenShot(): Bitmap {
setBackgroundColor(Color.WHITE)
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
draw(canvas)
return bitmap
}
it returns bitmap on which i am calling saveScreenShot which is another extenion function
fun Bitmap.saveScreenShot(
requireContext: Context,
filename: String,
ScreenShootFolderPath: String,
permissionListener: () -> Boolean,
): Uri? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
saveImageInQ(this, filename, ScreenShootFolderPath, requireContext.contentResolver)
else
legacySave(this, filename, ScreenShootFolderPath, permissionListener)
}
private fun saveImageInQ(
bitmap: Bitmap,
filename: String,
parentFileName: String,
contentResolver: ContentResolver
): Uri? {
val fos: OutputStream?
val uri: Uri?
val contentValues = ContentValues()
contentValues.apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.Files.FileColumns.MIME_TYPE, "image/png")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + parentFileName)
put(MediaStore.MediaColumns.IS_PENDING, 1)
}
uri =
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
uri?.let { contentResolver.openOutputStream(it) }.also { fos = it }
fos?.use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
fos?.flush()
fos?.close()
contentValues.clear()
contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0)
uri?.let {
contentResolver.update(it, contentValues, null, null)
}
return uri
}
private fun legacySave(
bitmap: Bitmap,
filename: String,
parentFileName: String,
permissionListener: () -> Boolean,
): Uri? {
val fos: OutputStream?
if (!permissionListener()) {
return null
}
val path =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() +
parentFileName + File.separator + filename
val imageFile = File(path)
if (imageFile.parentFile?.exists() == false) {
imageFile.parentFile?.mkdir()
}
imageFile.createNewFile()
fos = FileOutputStream(imageFile)
val uri: Uri = Uri.fromFile(imageFile)
fos.use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
fos.flush()
fos.close()
return uri
}
For all the Xamarin Users:
Xamarin.Android Code:
Create an external Class (I have an interface for each platform, and I implemented those 3 below functions from android platform):
public static Bitmap TakeScreenShot(View view)
{
View screenView = view.RootView;
screenView.DrawingCacheEnabled = true;
Bitmap bitmap = Bitmap.CreateBitmap(screenView.DrawingCache);
screenView.DrawingCacheEnabled = false;
return bitmap;
}
public static Java.IO.File StoreScreenShot(Bitmap picture)
{
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "MyFolderName";
var extFileName = Android.OS.Environment.ExternalStorageDirectory +
Java.IO.File.Separator +
Guid.NewGuid() + ".jpeg";
try
{
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
Java.IO.File file = new Java.IO.File(extFileName);
using (var fs = new FileStream(extFileName, FileMode.OpenOrCreate))
{
try
{
picture.Compress(Bitmap.CompressFormat.Jpeg, 100, fs);
}
finally
{
fs.Flush();
fs.Close();
}
return file;
}
}
catch (UnauthorizedAccessException ex)
{
Log.Error(LogPriority.Error.ToString(), "-------------------" + ex.Message.ToString());
return null;
}
catch (Exception ex)
{
Log.Error(LogPriority.Error.ToString(), "-------------------" + ex.Message.ToString());
return null;
}
}
public static void ShareImage(Java.IO.File file, Activity activity, string appToSend, string subject, string message)
{
//Push to Whatsapp to send
Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
Intent i = new Intent(Intent.ActionSendMultiple);
i.SetPackage(appToSend); // so that only Whatsapp reacts and not the chooser
i.AddFlags(ActivityFlags.GrantReadUriPermission);
i.PutExtra(Intent.ExtraSubject, subject);
i.PutExtra(Intent.ExtraText, message);
i.PutExtra(Intent.ExtraStream, uri);
i.SetType("image/*");
try
{
activity.StartActivity(Intent.CreateChooser(i, "Share Screenshot"));
}
catch (ActivityNotFoundException ex)
{
Toast.MakeText(activity.ApplicationContext, "No App Available", ToastLength.Long).Show();
}
}`
Now, from your Activity, you run the above code like this:
RunOnUiThread(() =>
{
//take silent screenshot
View rootView = Window.DecorView.FindViewById(Resource.Id.ActivityLayout);
Bitmap tmpPic = ShareHandler.TakeScreenShot(this.CurrentFocus); //TakeScreenShot(this);
Java.IO.File imageSaved = ShareHandler.StoreScreenShot(tmpPic);
if (imageSaved != null)
{
ShareHandler.ShareImage(imageSaved, this, "com.whatsapp", "", "ScreenShot Taken from: " + "Somewhere");
}
});
Hope it will be of use to anyone.
You can try the below code to capture the screenshot of current screen and share that image without any LIBRARY & PERMISSION. I have tested this its working perfectly.
Just copy paste this.
In MainAtivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button fullPageScreenshot, customPageScreenshot;
private LinearLayout rootContent;
private ImageView imageView;
private TextView hiddenText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build());
findViews();
implementClickEvents();
}
/* Find all views Ids */
private void findViews() {
fullPageScreenshot = (Button) findViewById(R.id.full_page_screenshot);
customPageScreenshot = (Button) findViewById(R.id.custom_page_screenshot);
rootContent = (LinearLayout) findViewById(R.id.root_content);
imageView = (ImageView) findViewById(R.id.image_view);
hiddenText = (TextView) findViewById(R.id.hidden_text);
}
/* Implement Click events over Buttons */
private void implementClickEvents() {
fullPageScreenshot.setOnClickListener(this);
customPageScreenshot.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.full_page_screenshot:
takeScreenshot(ScreenshotType.FULL);
break;
case R.id.custom_page_screenshot:
takeScreenshot(ScreenshotType.CUSTOM);
break;
}
}
/* Method which will take screenshot on Basis of Screenshot Type ENUM */
private void takeScreenshot(ScreenshotType screenshotType) {
Bitmap b = null;
switch (screenshotType) {
case FULL:
//If Screenshot type is FULL take full page screenshot i.e our root content.
b = ScreenshotUtils.getScreenShot(rootContent);
break;
case CUSTOM:
//If Screenshot type is CUSTOM
fullPageScreenshot.setVisibility(View.INVISIBLE);//set the visibility to INVISIBLE of first button
hiddenText.setVisibility(View.VISIBLE);//set the visibility to VISIBLE of hidden text
b = ScreenshotUtils.getScreenShot(rootContent);
//After taking screenshot reset the button and view again
fullPageScreenshot.setVisibility(View.VISIBLE);//set the visibility to VISIBLE of first button again
hiddenText.setVisibility(View.INVISIBLE);//set the visibility to INVISIBLE of hidden text
//NOTE: You need to use visibility INVISIBLE instead of GONE to remove the view from frame else it wont consider the view in frame and you will not get screenshot as you required.
break;
}
//If bitmap is not null
if (b != null) {
showScreenShotImage(b);//show bitmap over imageview
File saveFile = ScreenshotUtils.getMainDirectoryName(this);//get the path to save screenshot
File file = ScreenshotUtils.store(b, "screenshot" + screenshotType + ".jpg", saveFile);//save the screenshot to selected path
shareScreenshot(file);//finally share screenshot
} else
//If bitmap is null show toast message
Toast.makeText(this, R.string.screenshot_take_failed, Toast.LENGTH_SHORT).show();
}
/* Show screenshot Bitmap */
private void showScreenShotImage(Bitmap b) {
imageView.setImageBitmap(b);
}
/* Share Screenshot */
private void shareScreenshot(File file) {
Uri uri = Uri.fromFile(file);//Convert file path into Uri for sharing
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.sharing_text));
intent.putExtra(Intent.EXTRA_STREAM, uri);//pass uri here
startActivity(Intent.createChooser(intent, getString(R.string.share_title)));
}
}
ScreenshotType.java
public enum ScreenshotType {
FULL, CUSTOM;
}
ScreenshotUtils.java
public class ScreenshotUtils {
/* Method which will return Bitmap after taking screenshot. We have to pass the view which we want to take screenshot. */
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
/* Create Directory where screenshot will save for sharing screenshot */
public static File getMainDirectoryName(Context context) {
//Here we will use getExternalFilesDir and inside that we will make our Demo folder
//benefit of getExternalFilesDir is that whenever the app uninstalls the images will get deleted automatically.
File mainDir = new File(
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "Demo");
//If File is not present create directory
if (!mainDir.exists()) {
if (mainDir.mkdir())
Log.e("Create Directory", "Main Directory Created : " + mainDir);
}
return mainDir;
}
/* Store taken screenshot into above created path */
public static File store(Bitmap bm, String fileName, File saveFilePath) {
File dir = new File(saveFilePath.getAbsolutePath());
if (!dir.exists())
dir.mkdirs();
File file = new File(saveFilePath.getAbsolutePath(), fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
}
4.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context="com.takescreenshot_demo.MainActivity">
<!-- Button which will take full page screenshot -->
<Button
android:id="#+id/full_page_screenshot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/full_page_screenshot"
android:textColor="#android:color/white"
android:textSize="14sp" />
<!-- Hidden Text which will shown when taking screenshot from below Button -->
<TextView
android:id="#+id/hidden_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/hidden_text"
android:textColor="#android:color/white"
android:textSize="14sp"
android:visibility="invisible" />
<!-- Button which will take screenshot after hiding some view and showing some view -->
<Button
android:id="#+id/custom_page_screenshot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/custom_page_screenshot"
android:textColor="#android:color/white"
android:textSize="14sp" />
<!-- ImageView to show taken Screenshot -->
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
android:src="#mipmap/ic_launcher" />
</LinearLayout>
A consolidated copy and paste code:
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
String screenshotPath = mPath;
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
// openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
//Function to share Screenshot
private void shareScreenshots(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No App Available", Toast.LENGTH_SHORT).show();
}
}
//Function to open screenshot
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
This is how I captured the screen and shared it. Take a look if you are interested.
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
And the method that saves the bitmap image to external storage:
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}}
see more in : https://www.youtube.com/watch?v=LRCRNvzamwY&feature=youtu.be
If someone is getting an java.io.FileNotFoundException, following SilengKnight's solution, the problem is probably that writing in storage was not permited (Although we added the user-permission in the manifest). I solved it by adding this in the store function before making a new FileOutputStream.
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//Permission was denied
//Request for permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_CODE_EXTERNAL_STORAGE);
}
Create helper class for creating and sharing screen shot
public class share {
private final Context c;
public share(Context c) {
this.c = c;
}
public void shareInt(Bitmap bitmap, String msg, String name) {
Uri uri = getmageToShare(bitmap, name);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.putExtra(Intent.EXTRA_TEXT, msg);
intent.setType("*/*");
c.startActivity(Intent.createChooser(intent, "Share Via").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
// Retrieving the url to share
private Uri getmageToShare(Bitmap bitmap, String name) {
File imagefolder = new File(c.getCacheDir(), "images");
Uri uri = null;
try {
imagefolder.mkdirs();
File file = new File(imagefolder, name+".png");
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 70, outputStream);
outputStream.flush();
outputStream.close();
uri = FileProvider.getUriForFile(c, "com.yourapp.fileprovider", file);
} catch (Exception e) {
Toast.makeText(c, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
return uri;
}
}
Now call this helper class from any activity you want to take screen shot and share
CardView mainView = findViewById(R.id.mainView);
new share(c).shareInt(new getBitmap().screenShot(mainView), "msg", "randomstring");
here mainView is that view which you want to take snap shot, jzt pass view reference.
No need of run time permission coz we are using cache dir
This is what I use to take a screenshot. The solutions described above work fine for API < 24, but for API 24 and greater another solution is needed. I've tested this method on API 15, 24, & 27.
I placed the following methods in MainActivity.java:
public class MainActivity {
...
String[] permissions = new String[]{"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
View sshotView;
...
private boolean checkPermission() {
List arrayList = new ArrayList();
for (String str : this.permissions) {
if (ContextCompat.checkSelfPermission(this, str) != 0) {
arrayList.add(str);
}
}
if (arrayList.isEmpty()) {
return true;
}
ActivityCompat.requestPermissions(this, (String[]) arrayList.toArray(new String[arrayList.size()]), 100);
return false;
}
protected void onCreate(Bundle savedInstanceState) {
...
this.sshotView = getWindow().getDecorView().findViewById(R.id.parent);
...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_shareScreenshot:
boolean checkPermission = checkPermission();
Bitmap screenShot = getScreenShot(this.sshotView);
if (!checkPermission) {
return true;
}
shareScreenshot(store(screenShot));
return true;
case R.id.option2:
...
return true;
}
return false;
}
private void shareScreenshot(File file) {
Parcelable fromFile = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".com.redtiger.applehands.provider", file);
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setAction("android.intent.action.SEND");
intent.setType("image/*");
intent.putExtra("android.intent.extra.SUBJECT", XmlPullParser.NO_NAMESPACE);
intent.putExtra("android.intent.extra.TEXT", XmlPullParser.NO_NAMESPACE);
intent.putExtra("android.intent.extra.STREAM", fromFile);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Communication Platform Available", Toast.LENGTH_SHORT).show();
}
}
public static Bitmap getScreenShot(View view) {
View rootView = view.getRootView();
rootView.setDrawingCacheEnabled(true);
Bitmap createBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
return createBitmap;
public File store(Bitmap bitmap) {
String str = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Screenshots";
File file = new File(str);
if (!file.exists()) {
file.mkdirs();
}
file = new File(str + "/sshot.png");
try {
OutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "External Storage Permission Is Required", Toast.LENGTH_LONG).show();
}
return file;
}
}
I placed the following permissions and provider in my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.redtiger.applehands">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
...
<provider
android:name="com.redtiger.applehands.util.GenericFileProvider"
android:authorities="${applicationId}.com.redtiger.applehands.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
...
</application>
</manifest>
I created a file called provider_paths.xml (please see below) to direct the FileProvider where to save the screenshot. The file contains a simple tag that points to the root of the external directory.
The File was placed in the resource folder res/xml (if you don't have an xml folder here, just create one and place your file there).
provider_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
I am using a picture to display from web service.Now how to use image to set as profile picture of whatsapp or any other profile picture option. I am able to save and share an image. But how to provide an option in menu or as button to set picture as->
Similar to this which is used in Gallery..
I used for save and share button for image but don't know how to implement set profile photo.
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = activity.getExternalCacheDir();
File sharefile = new File(cache, "save.png"); //give your name and save it.
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
}
// Now send it out to share
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile));
try {
activity.startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
image.setDrawingCacheEnabled(true);
Bitmap bitmap = image.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/Nokia");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "Photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(activity, "Saved to your folder"+fotoname, Toast.LENGTH_SHORT ).show();
} catch (Exception e) {
}
}
});
On button Click :
OnButtonClick(){
ImageProcessing imageProcessing = new ImageProcessing();
Bitmap bitmap = imageProcessing.takeScreenshot(getWindow().getDecorView().findViewById(R.id.view_thought));
imageProcessing.saveBitmap(bitmap);
Intent intent = imageProcessing.setAsOption(this,imageProcessing.getSavedImagePath());
startActivityForResult(Intent.createChooser(intent, "Set image as"), 200);
}
Implement a new class ImageProcessing
public class ImageProcessing {
private File imagesPath;
public void saveBitmap(Bitmap bitmap) {
imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagesPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("POS", e.getMessage(), e);
} catch (IOException e) {
Log.e("POS", e.getMessage(), e);
}
}
public File getSavedImagePath(){
imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
return imagesPath;
}
public Bitmap takeScreenshot(View rootView) {
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public Intent setAsOption(Context cntxt,File imagesPath){
/*File imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");*/
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
if(imagesPath.exists()){
Uri contentUri = FileProvider.getUriForFile(cntxt, BuildConfig.APPLICATION_ID+".Utility.GenericFileProvider",imagesPath);
intent.setDataAndType(contentUri, "image/jpg");
intent.putExtra("mimeType", "image/jpg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}else {
Toast.makeText(cntxt,"Not a wallpaper",Toast.LENGTH_SHORT).show();
}
return intent;
}
}
In menifest add :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(Uri.parse("file:///" + yourFile), "image/jpg");
intent.putExtra("mimeType", "image/jpg");
startActivityForResult(Intent.createChooser(intent, "Set As"), 200);
I am working on a application in which I have to click the image from the camera and save it into directory.I am able to create directory named MyPersonalFolder and also images are going into it but when I am trying to open that image to see, it doesn't open and shows the message that that image cannot be opened. here is my code. Can anyone please tell me what mistake I am doing here.
I have also mentioned permissions in manifest .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
public class Camera extends Activity{
private static final String TAG = "Camera";
private static final int CAMERA_PIC_REQUEST = 1111;
Button click , share;
ImageView image;
String to_send;
String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
image = (ImageView)findViewById(R.id.image);
share = (Button)findViewById(R.id.share);
click = (Button)findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = getApplicationContext().getExternalCacheDir();
File sharefile = new File(cache, "toshare.png");
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
}
// Now send it out to share
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile.getAbsolutePath()));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
/*Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
//String to_send = null;
share.putExtra(Intent.EXTRA_TEXT, to_send);
startActivity(Intent.createChooser(share, "Share using..."));*/
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
FileOutputStream outStream = null;
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(thumbnail);
//3
share.setVisibility(0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyPersonalFolder");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
//outStream.write(data[0]);
outStream.flush();
outStream.close();
//Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();*/
}
}
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
}
You will need to use MediaScanner to notify the system of the new file/directory. You can try something like this after creating and saving the new file:
/**
* Adds the new photo/video to the device gallery, else it will remain only visible via sd card
*
* #param path
*/
public static void addToGallery(Context context, String path) {
MediaScanner scanner = new MediaScanner(path, null);
MediaScannerConnection connection = new MediaScannerConnection(context, scanner);
scanner.connection = connection;
connection.connect();
}
/**
* Scans the sd card for new videos/images and adds them to the gallery
*/
private static final class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private final String path;
private final String mimeType;
MediaScannerConnection connection;
public MediaScanner(String path, String mimeType) {
this.path = path;
this.mimeType = mimeType;
}
#Override
public void onMediaScannerConnected() {
connection.scanFile(path, mimeType);
}
#Override
public void onScanCompleted(String path, Uri uri) {
connection.disconnect();
}
}
EDIT:
You are also forgetting to write the byte array to the file specified in the output stream, like in the code that you have commented out. Try this at the end just before you refresh the gallery:
outStream = new FileOutputStream(outFile);
outStream.write(bytes.toByteArray()); //this is the line you had missing
outStream.flush();
outStream.close();
Also take note that using Intent.ACTION_MEDIA_SCANNER_SCAN_FILE to refresh the gallery can also present you with some security issues on kitkat (cant remember exactly what the issues were). So just make sure you test it on kitkat device to confirm that it works correctly