how to pass an entire activity in android studio - java

I am developing an android app and I'am trying to make the following code works. What i want to do is: taking screenshot of the whole activity including the text that is not being shown (have to scroll up or down).
This is the screenshot method:
public static Bitmap takeScreenshot(Activity activity){
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
Bitmap bmap = view.getDrawingCache();
Rect statusBar = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(statusBar);
Bitmap snapshot = Bitmap.createBitmap(bmap, 0, statusBar.top, bmap.getWidth(), bmap.getHeight() - statusBar.top, null, true);
view.setDrawingCacheEnabled(false);
return snapshot;
}
public void saveBitmap(Bitmap bitmap) {
File 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);
}
}
I want to call takeScreenshot on the following function, but i don't know how to pass an activity in takeScreenshot's parameter. Ive tried to copy the name of the activity and it didn't work.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed__info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
id = intent.getStringExtra(Urls.MARKER_ID);
year = intent.getStringExtra(Urls.MARKER_Year);
info = intent.getStringExtra(Urls.MARKER_Info);
editTextName = (TextView) findViewById(R.id.markerYear);
editTextDesg = (TextView) findViewById(R.id.detailedInfo);
editTextName.setText(year);
editTextDesg.setText(info);
//Saving into picture
findViewById(R.id.download).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot(); // here's where i have to pass the activity
saveBitmap(bitmap);
}
});
}

Passing Activity is same as you pass the context of the current activity. You just need to this within your Activity:
takeScreenshot(this)

Just pass the activity context in the method.
Bitmap bitmap = takeScreenshot(MyActivity.this); would work for you.
Update
public static Bitmap takeScreenshot(Activity activity) {
try {
// create bitmap screen capture
View v1 = activity.getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
return bitmap;
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
return null;
}

Try this for capturing screenshot:
public static Bitmap captureScreen(View v) {
Bitmap screenshot = null;
try {
if(v!=null) {
screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),v.getMeasuredHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
v.draw(canvas);
}
}catch (Exception e){
Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
}
return screenshot;
}
public static void saveImage(Bitmap bitmap) throws IOException{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
For further reference visit the below link:
http://karanbalkar.com/2014/03/get-screenshot-of-device-screen-in-android/

Related

How to take a screenshot on Android?

I am trying to take a screenshot using the code below, I click the button takeScreenshot() is attached to but nothing happens.
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";
// 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();
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
Try this, first create class:
public class TakeScreenshot {
public static Bitmap takescreenshot(View view) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return b;
}
public static Bitmap takescreenshotofview(View view) {
return takescreenshot(view.getRootView());
}}
And in MainActivity:
public void onClick(View view) {
Bitmap b = TakeScreenshot.takescreenshotview(imageView);
imageView.setImageBitmap(b);
}

Save the image to internal storage, obtain and open it in the gallery app

I want to save an image in the internal memory of the phone and then open it in the default image viewer. The gallery opens with a black screen. Reviewing the picture on the Android Device Monitor, is in the following path: "/data/data/com.myapp.myappname/app_ImageTest/test.jpg" transfer it to the computer and the image opens properly.
This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test);
path_absolute = saveToInternalStorage(bitmap);
}
public void open_photo(View v) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.parse("file://" + path_absolute );
intent.setDataAndType(uri,"image/*");
startActivity(intent);
}
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("ImageTest", Context.MODE_WORLD_READABLE);
File mypath=new File(directory,"test.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
Would welcome a detailed explanation, I'm newbies on Android. Thank you!

How can I take a screenshot of my screen and save it on Internal Storage? Android

I am implementing a button which lets you take a screenshot, but I want to save it on the Android Internal Storage not in the External Storage (SD Card).
I tried this:
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.close();
}
return directory.getAbsolutePath();
}
I've started this method with an OnClick method of a button:
private void takeScreenshot(View v) {
v = getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
saveToInternalStorage(bitmap)
}
But this didn't work. Instead, when I click the button, an error message appears on my cell phone: "Application has stopped".
Hope you can help me.
I think you need to use openFileOutput to get a FileOutputStream, try following the example in the doc https://developer.android.com/training/basics/data-storage/files.html
What's the error in the logcat?
/**
* This function captures any Android views to a bitmap shapshot
* and save it to a file path
* and optionally open it with android pciture viewer
*/
public void CaptureView(View view, String filePath, boolean bOpen) {
view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();
try {
b.compress(CompressFormat.JPEG, 95, new FileOutputStream(filePath));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bOpen) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + filePath), "image/*");
startActivity(intent);
}
}
Usage:
File sdcard = Environment.getExternalStorageDirectory();
String path = sdcard + "/demo.jpg";
CaptureView(someViewInstace, path, false);
You can use Context.getFilesDir() method to get the path to the internal storage:
String path = yourActivity.getFilesDir() + "/" + name);
Add permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
add this line manifest file application tag
android:requestLegacyExternalStorage="true"
In activity
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int permission = ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
MainActivity.this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
} else {
takeScreenshot();
}
}
});
}
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";
// 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();
Toast.makeText(MainActivity.this, "Successfully saved", Toast.LENGTH_SHORT).show();
//**if you want to open this screenshot
openScreenshot(imageFile);
} catch (Throwable e) {
e.printStackTrace();
}
}
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);
}
}

Screenshot Black in Android

I've been working out how to take a screenshot programmatically in android, however when it screenshots I get a toolbar and black screen captured instead of what is actually on the screen.
I've also tried to screenshot a particular TextView within the custom InfoWindow layout I created for the google map. But that creates a null pointer exception on the second line below.
TextView v1 = (TextView)findViewById(R.id.tv_code);
v1.setDrawingCacheEnabled(true);
Is there anyway to either actually screenshot what is on the screen without installing android screenshot library or to screenshot a TextView within a custom InfoWindow layout
This is my screenshot method:
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: I have changed the method to the one provided from the source
How can i take/merge screen shot of Google map v2 and layout of xml both programmatically?
However it does not screenshot anything.
public void captureMapScreen() {
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap snapshot) {
try {
View mView = getWindow().getDecorView().getRootView();
mView.setDrawingCacheEnabled(true);
Bitmap backBitmap = mView.getDrawingCache();
Bitmap bmOverlay = Bitmap.createBitmap(
backBitmap.getWidth(), backBitmap.getHeight(),
backBitmap.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(backBitmap, 0, 0, null);
canvas.drawBitmap(snapshot, new Matrix(), null);
FileOutputStream out = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/"
+ System.currentTimeMillis() + ".jpg");
bmOverlay.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
mMap.snapshot(callback);
}
Use this code
private void takeScreenshot() {
AsyncTask<Void, Void, Void> asyc = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
objUsefullData.showProgress("Please wait", "");
}
#Override
protected Void doInBackground(Void... params) {
try {
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmapscreen_shot = Bitmap.createBitmap(v1
.getDrawingCache());
v1.setDrawingCacheEnabled(false);
String state = Environment.getExternalStorageState();
File folder = null;
if (state.contains(Environment.MEDIA_MOUNTED)) {
folder = new File(
Environment.getExternalStorageDirectory()
+ "/piccapella");
} else {
folder = new File(
Environment.getExternalStorageDirectory()
+ "/piccapella");
}
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Create a media file name
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.getDefault())
.format(new java.util.Date());
imageFile = new File(folder.getAbsolutePath()
+ File.separator + "IMG_" + timeStamp + ".jpg");
/*
* Toast.makeText(AddTextActivity.this,
* "saved Image path" + "" + imageFile,
* Toast.LENGTH_SHORT) .show();
*/
imageFile.createNewFile();
} else {
/*
* Toast.makeText(AddTextActivity.this,
* "Image Not saved", Toast.LENGTH_SHORT).show();
*/
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
// save image into gallery
bitmapscreen_shot.compress(CompressFormat.JPEG, 100,
ostream);
FileOutputStream fout = new FileOutputStream(imageFile);
fout.write(ostream.toByteArray());
fout.close();
Log.e("image_screen_shot", "" + imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
objUsefullData.dismissProgress();
}
};
asyc.execute();
}
Hope this will help you
I have figured it out !
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap bitmap) {
Bitmap b = bitmap;
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.getDefault())
.format(new java.util.Date());
String filepath = timeStamp + ".jpg";
try{
OutputStream fout = null;
fout = openFileOutput(filepath,MODE_WORLD_READABLE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
saveImage(filepath);
}
};
mMap.snapshot(callback);
}
/**
* Method to save the screenshot image
* #param filePath the file path
*/
public void saveImage(String filePath)
{
File file = this.getFileStreamPath(filePath);
if(!filePath.equals(""))
{
final ContentValues values = new ContentValues(2);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
final Uri contentUriFile = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(HuntActivity.this,"Code Saved to files!",Toast.LENGTH_LONG).show();
}
else
{
System.out.println("ERROR");
}
}
I have adapted the code from this link so it doesn't share and instead just saves the image.
Capture screen shot of GoogleMap Android API V2
Thanks for everyones help
Please try with the code below:
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
Bitmap bitmap = null;
Bitmap bitmap1 = null;
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
try {
if (bitmap != null)
bitmap1 = Bitmap.createBitmap(bitmap, 0, 0,
v1.getWidth(), v1.getHeight());
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I faced this issue. After v1.setDrawingCacheEnabled(true); I added,
v1.buildDrawingCache();
And put some delay to call the takeScreenshot(); method.
It is fixed.

Universal Image Loader - Save Image to SD-Card

I'm using the universal image loader for my app. I want to save the current image displayed by the ViewPager to the SD-Card however the code I have below is saving the wrong image to the SD-Card. It saves the images at random only. I need to way of knowing how to retrieve the current bitmap of the image and saving it. I don't know any other alternatives of getting the bitmap of the current image and saving it to the SD-Card. The way I'm getting the bitmap currently is through "Bitmap bitmap = loadedImage". Your help would be greatly appreciated. Cheeers.
public class ImagePagerFragment extends BaseFragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fr_image_pager, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(new ImageAdapter());
pager.setCurrentItem(getArguments().getInt(Constants.Extra.IMAGE_POSITION, 0));
return rootView;
}
private class ImageAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
assert imageLayout != null;
final christ.triumphant.TouchImageView imageView = (christ.triumphant.TouchImageView) imageLayout.findViewById(R.id.imagei);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
ImageLoader.getInstance().displayImage(imageUrls[position], imageView, options, new SimpleImageLoadingListener() {
..
#Override
public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
isave = (Button) getView().findViewById(R.id.save);
isave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Bitmap bitmap = loadedImage;
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/HD GOSPEL LOCKSCREENS");
File f = new File(folder, String.valueOf(System.currentTimeMillis()) + "HDGL.PNG");
try {
FileOutputStream out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(getActivity(), "Image Successfully Saved", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File ff = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(ff);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
else
{
getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ishare = (Button) getView().findViewById(R.id.share);
ishare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Bitmap icon = loadedImage;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
Toast.makeText(getActivity(), "Image Successfully Shared", Toast.LENGTH_LONG).show();
}
});
}
});
view.addView(imageLayout, 0);
return imageLayout;
}
... ... ... }

Categories