How can I save only the last taken image to directory? - java

Here I have created an app to take images and save them to external storage of the phone. (Also there is a problem with below code that images are not saved to the given location.) I want only the last taken image to be saved in external memory of the phone.Everytime I take a new picture, I need to delete the previously taken image and save only the last taken image. How can I do it? Also is it possible to take images continously at regular intervals? I searched and I found that I can do it with a Timer(). Is it possible? Thank You.
Edit- Actually what I want is to comapare two images. One is taken at the moment and other is taken immediately before it. (I take images at regular time intervals and I compare new one with the previous one.) Only after comparison, I delete previous one.
public class MyCamera extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* #return
*/
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, e.getMessage());
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String fname = "IMG_" + timeStamp + ".jpg";
System.out.println(fname);
File mediaFile;
mediaFile = new File(mediaStorageDir, fname);
return mediaFile;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_camera, menu);
return true;
}
}

You can keep a constant name for your photo file.
String fname = "MyImage.jpg";
You can give some constant name. And about taking image at regular interval, you can use handler.
You can read more about it here.
And make sure your remove your handler when your camera is closed.
EDITED
You can list the files of your directory,mediaStorageDir in your case.
List all the files of the directory, and delete the file which is older by comparing the last modified.

Related

How I can prompt a file manager into a known path in an android app?

I have the following activity in my application:
public class DisplaySettingsActivity extends AppCompatActivity implements View.OnClickListener {
Button saveIntoFile;
TextView msg;
private ActivityResultLauncher<String> requestPermissionLauncher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_settings);
requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
Log.d("H300s","Permissions Callback");
if (isGranted) {
Log.d("H300s","Permission Accepted 2");
saveFile();
} else {
permissionSaveDenied();
}
});
this.saveIntoFile = (Button)findViewById(R.id.save);
this.saveIntoFile.setOnClickListener(this);
}
private void saveFile(){
Log.d("Η300s","Saving");
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.e("H300s","Unable to detect external storage");
saveMsgHandler(null);
return;
}
this.saveIntoFile.setEnabled(false);
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyMMdd");
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
file = new File( file.getAbsolutePath(),"voip_h300s_"+pattern.format(LocalDate.now())+".txt");
Log.d("H300s",file.toString());
try {
file.createNewFile();
PrintWriter out = new PrintWriter(new FileWriter(file));
out.println("SOME VALUES");
out.close();
saveMsgHandler(file.getAbsolutePath());
} catch (Exception e) {
saveMsgHandler(null);
}
}
#Override
public void onBackPressed() {
return;
}
private void saveMsgHandler(String savePath){
if (savePath == null) {
msg.setText(R.string.could_not_save_settings);
int errorColor = ContextCompat.getColor(this, R.color.error);
msg.setBackgroundColor(errorColor);
} else {
String string = String.format(getString(R.string.save_success),savePath);
msg.setText(string);
int success = ContextCompat.getColor(this, R.color.success);
msg.setBackgroundColor(success);
}
msg.setVisibility(View.VISIBLE);
this.saveIntoFile.setEnabled(true);
}
private void permissionSaveDenied(){
msg.setVisibility(View.VISIBLE);
msg.setText(R.string.could_not_save_settings);
int errorColor = ContextCompat.getColor(this, R.color.error);
msg.setBackgroundColor(errorColor);
this.saveIntoFile.setEnabled(true);
}
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d("H300s","Permission Accepted");
saveFile();
} else {
requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE );
}
}
}
And I want once I save the file to be able to prompt into androids file manager and list the saved file. Any provided solution tells me hot to select a path before saving as seen in this answer or in this question, but instead I want just to show the file into device's file manager after I successfully saving it.
So far, what I've developed is this method:
public void displayFileIntoFileManager(String path){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivity(intent, 7);
}
As a method to call from a button, once I saved the file in saveFile method. But how I can provide the path to the intent in order to be shown?
I just want to list the file into device's file manager.
I want just to show the file into device's file manager after I successfully saving it.
There is no standard Intent action for "open a file manager on a directory containing a specific file", sorry.
So far, what I've developed is this method
ACTION_GET_CONTENT is to allow the user to select a piece of content. If you are not looking to have the user do that, then this is not a suitable Intent action.
How I can prompt a file manager into a known path in an android app?
Wrong question.
You should have asked:
How can i let ACTION_GET_CONTENT, ACTION_OPEN_DOCUMENT and ACTION_OPEN_DOCUMENT_TREE open in a pre determined directory?
That question has been answered before.
The trick is to use extra INITIAL_URI.

Proper way how to get image from gallery and captured photos?

My attempt does not work at all unfortunately. Weirdly enough, capturing photos from camera works when debugging but does not in production.
#Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (!Debug.isDebuggerConnected()){
Debug.waitForDebugger();
Log.d("debug", "started"); // Insert a breakpoint at this line!!
}
if (resultCode != RESULT_OK) {
return;
}
File file = null;
Uri path = null;
Bitmap image = null;
switch (requestCode) {
case RequestCodes.REQUEST_IMAGE_CAPTURE:
Bundle extras = data.getExtras();
image = (Bitmap) extras.get("data");
file = ImageUtils.saveToFile(image, "profile_picture", this);
mProfileImageView.setImageBitmap(image);
mCurrentAbsolutePath = file.getAbsolutePath();
break;
case RequestCodes.REQUEST_IMAGE_SELECT:
path = data.getData();
mProfileImageView.setImageURI(path);
mCurrentAbsolutePath = path.getPath();
file = new File(mCurrentAbsolutePath);
image = BitmapFactory.decodeFile(mCurrentAbsolutePath, new BitmapFactory.Options());
break;
default:
break;
}
try {
if(RequestCodes.REQUEST_IMAGE_SELECT == requestCode){
file = File.createTempFile(
"user_picture", /* prefix */
".jpeg", /* suffix */
getExternalFilesDir(Environment.DIRECTORY_PICTURES) /* directory */
);
File pathFile = new File(ImageUtils.getPath(path, this));
GeneralUtils.copy(pathFile, file);
}
} catch (IOException e) {
e.printStackTrace();
}
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(image, 100, 100);
String thumbnailPath = null;
// Edited source: https://stackoverflow.com/a/673014/6519101
FileOutputStream out = null;
try {
// PNG is a lossless format, the compression factor (100) is ignored
thumbnailPath = File.createTempFile(
"user_picture_thumbnail", /* prefix */
".png", /* suffix */
getExternalFilesDir(Environment.DIRECTORY_PICTURES) /* directory */
).getAbsolutePath();
out = new FileOutputStream(thumbnailPath);
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
String finalPath = file.getPath();
UserClient client = new UserClient();
String finalThumbnailPath = thumbnailPath;
client.changeUserPicture(file, FileUtils.getMimeType(this, Uri.fromFile(file)), new ApiListener<Response<ResponseBody>>(this){
#Override
public void onSuccess(Response<ResponseBody> response, int statusCode) {
SharedPreferencesManager preferences = SharedPreferencesManager.getInstance();
preferences.put(SharedPreferencesManager.Key.ACCOUNT_IMAGE_PATH, finalPath);
preferences.put(SharedPreferencesManager.Key.ACCOUNT_IMAGE_THUMBNAIL_PATH, finalThumbnailPath);
super.onSuccess(response, statusCode);
}
});
}
Unfortunately when debugging the from example of a path "/0/4/content://media/external/images/media/54257/ORIGINAL/NONE/1043890606" decoded file end up being null and breaks everything.
What is the best way of both getting from gallery and capturing image from photo?
What you should be using are content providers and resolvers here which can be thought of as databases and accessing databases for easier understanding.
That path you have there is called a URI, which is essentially like a link to a database entry. Both the camera and gallery uses content providers and resolvers actively. When a photo is taken, it is saved but the camera app also lets content provider know a new entry has been added. Now every app who has the content resolvers, such as the gallery app, can find that photo because the URI exist.
So you should be following the guides to implement content resolver if you want to access all photos in gallery.
As an aside, if you use code to copy an image file but does up update the content providers, your other app cannot see that new copied file unless it knows the absolute path. But when you restart your phone, some system does a full recheck for all image files and your content provider could be updated with the newly copied file. So try restarting your phone when testing.

taking a photo and placing it in the Gallery

I have an app which displays its own subclass of SurfaceView with a camera preview, and has its own capture button. I use Camera.takePicture to take the picture, and in the onPictureTaken callback, feed the image data directly into MediaStore.Images.Media.insertImage. (That seemed simpler than writing the image to file and then adding it to the Gallery, but maybe it's a bad idea.)
And the picture shows up in the Gallery! However, it's at the end of the Gallery, which makes it very hard to find. I'd like it to show up at the beginning of the gallery, just like a picture taken with the regular Camera app.
As far as I can tell, the problem is that the stock Camera app names the files as IMG_YYYYMMDD_[time].jpg, while my photos end up as [unix timestamp].jpg. But I don't know how to tell MediaStore to fix that.
Here is the code:
public void capture() {
mCamera.takePicture(null, null, mPicture);
}
final PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
MediaStore.Images.Media.insertImage(getContentResolver(),
BitmapFactory.decodeByteArray(data, 0, data.length),
null, null);
}
};
The actual solution was to add date metadata. The final result (which still contains an orientation bug) is
final PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Create a media file name
String title = "IMG_"+ new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String DCIM = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString();
String DIRECTORY = DCIM + "/Camera";
String path = DIRECTORY + '/' + title + ".jpg";
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
out.write(data);
} catch (Exception e) {
Log.e("pictureTaken", "Failed to write data", e);
} finally {
try {
out.close();
} catch (Exception e) {
Log.e("pictureTaken", "Failed to close file after write", e);
}
}
// Insert into MediaStore.
ContentValues values = new ContentValues(5);
values.put(ImageColumns.TITLE, title);
values.put(ImageColumns.DISPLAY_NAME, title + ".jpg");
values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
values.put(ImageColumns.DATA, path);
// Clockwise rotation in degrees. 0, 90, 180, or 270.
values.put(ImageColumns.ORIENTATION, activity.getWindowManager().getDefaultDisplay()
.getRotation() + 90);
Uri uri = null;
try {
uri = activity.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (Throwable th) {
// This can happen when the external volume is already mounted, but
// MediaScanner has not notify MediaProvider to add that volume.
// The picture is still safe and MediaScanner will find it and
// insert it into MediaProvider. The only problem is that the user
// cannot click the thumbnail to review the picture.
Log.e("pictureTaken", "Failed to write MediaStore" + th);
}
}
};

how can i take a screen shot of current mobile screen View through Service (background process) Android [duplicate]

How can I take a screenshot of a selected area of phone-screen not by any program but from code?
Here is the code that allowed my screenshot to be stored on an SD card and used later for whatever your needs are:
First, you need to add a proper permission to save the file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an Activity):
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();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
And this is how you can open the recently generated image:
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);
}
If you want to use this on fragment view then use:
View v1 = getActivity().getWindow().getDecorView().getRootView();
instead of
View v1 = getWindow().getDecorView().getRootView();
on takeScreenshot() function
Note:
This solution doesn't work if your dialog contains a surface view. For details please check the answer to the following question:
Android Take Screenshot of Surface View Shows Black Screen
Call this method, passing in the outer most ViewGroup that you want a screen shot of:
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Note: works only for rooted phone
Programmatically, you can run adb shell /system/bin/screencap -p /sdcard/img.png as below
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
then read img.png as Bitmap and use as your wish.
No root permission or no big coding is required for this method.
On adb shell using below command you can take screen shot.
input keyevent 120
This command does not required any root permission so same you can perform from java code of android application also.
Process process;
process = Runtime.getRuntime().exec("input keyevent 120");
More about keyevent code in android see http://developer.android.com/reference/android/view/KeyEvent.html
Here we have used. KEYCODE_SYSRQ its value is 120 and used for System Request / Print Screen key.
As CJBS said, The output picture will be saved in /sdcard/Pictures/Screenshots
Mualig answer is very good, but I had the same problem Ewoks describes, I'm not getting the background. So sometimes is good enough and sometimes I get black text over black background (depending on the theme).
This solution is heavily based in Mualig code and the code I've found in Robotium. I'm discarding the use of drawing cache by calling directly to the draw method. Before that I'll try to get the background drawable from current activity to draw it first.
// Some constants
final static String SCREENSHOTS_LOCATIONS = Environment.getExternalStorageDirectory().toString() + "/screenshots/";
// Get device dimmensions
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
// Get root view
View view = mCurrentUrlMask.getRootView();
// Create the bitmap to use to draw the screenshot
final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_4444);
final Canvas canvas = new Canvas(bitmap);
// Get current theme to know which background to use
final Activity activity = getCurrentActivity();
final Theme theme = activity.getTheme();
final TypedArray ta = theme
.obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
final int res = ta.getResourceId(0, 0);
final Drawable background = activity.getResources().getDrawable(res);
// Draw background
background.draw(canvas);
// Draw views
view.draw(canvas);
// Save the screenshot to the file system
FileOutputStream fos = null;
try {
final File sddir = new File(SCREENSHOTS_LOCATIONS);
if (!sddir.exists()) {
sddir.mkdirs();
}
fos = new FileOutputStream(SCREENSHOTS_LOCATIONS
+ System.currentTimeMillis() + ".jpg");
if (fos != null) {
if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
Log.d(LOGTAG, "Compress/Write failed");
}
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
As a reference, one way to capture the screen (and not just your app activity) is to capture the framebuffer (device /dev/graphics/fb0). To do this you must either have root privileges or your app must be an app with signature permissions ("A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission") - which is very unlikely unless you compiled your own ROM.
Each framebuffer capture, from a couple of devices I have tested, contained exactly one screenshot. People have reported it to contain more, I guess it depends on the frame/display size.
I tried to read the framebuffer continuously but it seems to return for a fixed amount of bytes read. In my case that is (3 410 432) bytes, which is enough to store a display frame of 854*480 RGBA (3 279 360 bytes). Yes, the frame, in binary, outputted from fb0 is RGBA in my device. This will most likely depend from device to device. This will be important for you to decode it =)
In my device /dev/graphics/fb0 permissions are so that only root and users from group graphics can read the fb0.
graphics is a restricted group so you will probably only access fb0 with a rooted phone using su command.
Android apps have the user id (uid) = app_## and group id (guid) = app_## .
adb shell has uid = shell and guid = shell, which has much more permissions than an app. You can actually check those permissions at /system/permissions/platform.xml
This means you will be able to read fb0 in the adb shell without root but you will not read it within the app without root.
Also, giving READ_FRAME_BUFFER and/or ACCESS_SURFACE_FLINGER permissions on AndroidManifest.xml will do nothing for a regular app because these will only work for 'signature' apps.
Also check this closed thread for more details.
private void captureScreen() {
View v = getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
try {
FileOutputStream fos = new FileOutputStream(new File(Environment
.getExternalStorageDirectory().toString(), "SCREEN"
+ System.currentTimeMillis() + ".png"));
bmp.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Add the permission in the manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
For Supporting Marshmallow or above versions, please add the below code in the activity onCreate method
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},00);
My solution is:
public static Bitmap loadBitmapFromView(Context context, View v) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
return returnedBitmap;
}
and
public void takeScreen() {
Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
}
Images are saved in the external storage folder.
You can try the following library:
http://code.google.com/p/android-screenshot-library/
Android Screenshot Library (ASL) enables to programmatically capture screenshots from Android devices without requirement of having root access privileges. Instead, ASL utilizes a native service running in the background, started via the Android Debug Bridge (ADB) once per device boot.
Based on the answer of #JustinMorris above and #NiravDangi here https://stackoverflow.com/a/8504958/2232148 we must take the background and foreground of a view and assemble them like this:
public static Bitmap takeScreenshot(View view, Bitmap.Config quality) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), quality);
Canvas canvas = new Canvas(bitmap);
Drawable backgroundDrawable = view.getBackground();
if (backgroundDrawable != null) {
backgroundDrawable.draw(canvas);
} else {
canvas.drawColor(Color.WHITE);
}
view.draw(canvas);
return bitmap;
}
The quality parameter takes a constant of Bitmap.Config, typically either Bitmap.Config.RGB_565 or Bitmap.Config.ARGB_8888.
public class ScreenShotActivity extends Activity{
private RelativeLayout relativeLayout;
private Bitmap myBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = (RelativeLayout)findViewById(R.id.relative1);
relativeLayout.post(new Runnable() {
public void run() {
//take screenshot
myBitmap = captureScreen(relativeLayout);
Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();
try {
if(myBitmap!=null){
//save image to SD card
saveImage(myBitmap);
}
Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
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();
}
}
ADD PERMISSION
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can try to do something like this,
Getting a bitmap cache from a layout or a view by doing something like
First you gotta setDrawingCacheEnabled to a layout(a linearlayout or relativelayout, or a view)
then
Bitmap bm = layout.getDrawingCache()
Then you do whatever you want with the bitmap. Either turning it into an image file, or send the bitmap's uri to somewhere else.
Short way is
FrameLayout layDraw = (FrameLayout) findViewById(R.id.layDraw); /*Your root view to be part of screenshot*/
layDraw.buildDrawingCache();
Bitmap bmp = layDraw.getDrawingCache();
Most of the answers for this question use the the Canvas drawing method or drawing cache method. However, the View.setDrawingCache() method is deprecated in API 28. Currently the recommended API for making screenshots is the PixelCopy class available from API 24 (but the methods which accept Window parameter are available from API 26 == Android 8.0 Oreo). Here is a sample Kotlin code for retrieving a Bitmap:
#RequiresApi(Build.VERSION_CODES.O)
fun saveScreenshot(view: View) {
val window = (view.context as Activity).window
if (window != null) {
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
val locationOfViewInWindow = IntArray(2)
view.getLocationInWindow(locationOfViewInWindow)
try {
PixelCopy.request(window, Rect(locationOfViewInWindow[0], locationOfViewInWindow[1], locationOfViewInWindow[0] + view.width, locationOfViewInWindow[1] + view.height), bitmap, { copyResult ->
if (copyResult == PixelCopy.SUCCESS) {
saveBitmap(bitmap)
}
// possible to handle other result codes ...
}, Handler())
} catch (e: IllegalArgumentException) {
// PixelCopy may throw IllegalArgumentException, make sure to handle it
}
}
}
For those who want to capture a GLSurfaceView, the getDrawingCache or drawing to canvas method won't work.
You have to read the content of the OpenGL framebuffer after the frame has been rendered. There is a good answer here
I have created a simple library that takes a screenshot from a View and either gives you a Bitmap object or saves it directly to any path you want
https://github.com/abdallahalaraby/Blink
If you want to take screenshot from fragment than follow this:
Override onCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
mView = view;
}
Logic for taking screenshot:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = mView.findViewById(R.id.scrollView1);
shareScreenShotM(view, (NestedScrollView) view);
}
method shareScreenShotM)():
public void shareScreenShotM(View view, NestedScrollView scrollView){
bm = takeScreenShot(view,scrollView); //method to take screenshot
File file = savePic(bm); // method to save screenshot in phone.
}
method takeScreenShot():
public Bitmap takeScreenShot(View u, NestedScrollView z){
u.setDrawingCacheEnabled(true);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
Log.d("yoheight",""+ totalHeight);
Log.d("yowidth",""+ totalWidth);
u.layout(0, 0, totalWidth, totalHeight);
u.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
u.setDrawingCacheEnabled(false);
u.destroyDrawingCache();
return b;
}
method savePic():
public static File savePic(Bitmap bm){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File sdCardDirectory = new File(Environment.getExternalStorageDirectory() + "/Foldername");
if (!sdCardDirectory.exists()) {
sdCardDirectory.mkdirs();
}
// File file = new File(dir, fileName);
try {
file = new File(sdCardDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
file.createNewFile();
new FileOutputStream(file).write(bytes.toByteArray());
Log.d("Fabsolute", "File Saved::--->" + file.getAbsolutePath());
Log.d("Sabsolute", "File Saved::--->" + sdCardDirectory.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
For activity you can simply use View v1 = getWindow().getDecorView().getRootView(); instead of mView
Just extending taraloca's answer. You must add followings lines to make it work. I have made the image name static. Please ensure you use taraloca's timestamp variable incase you need dynamic image name.
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private void verifyStoragePermissions() {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}else{
takeScreenshot();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == REQUEST_EXTERNAL_STORAGE) {
takeScreenshot();
}
}
}
And in the AndroidManifest.xml file following entries are must:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For Full Page Scrolling Screenshot
If you want to capture a full View screenshot (Which contains a scrollview or so) then have a check at this library
https://github.com/peter1492/LongScreenshot
All you have to do is import the Gradel, and create an object of BigScreenshot
BigScreenshot longScreenshot = new BigScreenshot(this, x, y);
A callback will be received with the bitmap of the Screenshots taken while automatically scrolling through the screen view group and at the end assembled together.
#Override public void getScreenshot(Bitmap bitmap) {}
Which can be saved to the gallery or whatsoever usage is necessary their after
For system applications only!
Process process;
process = Runtime.getRuntime().exec("screencap -p " + outputPath);
process.waitFor();
Note: System applications don't need to run "su" to execute this command.
The parameter view is the root layout object.
public static Bitmap screenShot(View view) {
Bitmap bitmap = null;
if (view.getWidth() > 0 && view.getHeight() > 0) {
bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
}
return bitmap;
}
From Android 11 (API level 30) you can take screen shot with the accessibility service:
takeScreenshot - Takes a screenshot of the specified display and returns it via an AccessibilityService.ScreenshotResult.
Take screenshot of a view in android.
public static Bitmap getViewBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
If you want to capture screenshot of a View, use View::drawToBitmap extension function:
val bitmap = myTargetView.drawToBitmap(/*Optional:*/ Bitmap.Config.ARGB_8888)
Only make sure to use the -ktx version of AndroidX Core library:
implementation("androidx.core:core-ktx:1.6.0")
I've already answered a similar question like this here.
Kotlin
private fun screenShot() {
try {
val mPath: String = this.getExternalFilesDir(null).getAbsolutePath()
.toString() + "/temp" + ".png"
// create bitmap screenshot
val v1: View = getWindow().getDecorView().getRootView()
v1.isDrawingCacheEnabled = true
val bitmap = Bitmap.createBitmap(v1.drawingCache)
v1.isDrawingCacheEnabled = false
val imageFile = File(mPath)
val outputStream = FileOutputStream(imageFile)
val quality = 100
bitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream)
outputStream.flush()
outputStream.close()
//or you can share to test the method fast
val uriPath =
FileProvider.getUriForFile(this, getPackageName() + ".sharing.provider", imageFile)
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*"
intent.clipData = ClipData.newRawUri("", uriPath)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
intent.putExtra(Intent.EXTRA_STREAM, uriPath)
startActivity(Intent.createChooser(intent, "Sharing to..."))
} catch (e: Throwable) {
e.printStackTrace()
}
}
Java
private void screenShot() {
try {
String mPath = this.getExternalFilesDir(null).getAbsolutePath().toString() + "/temp" + ".png";
// create bitmap screenshot
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.PNG, quality, outputStream);
outputStream.flush();
outputStream.close();
//or you can share to test the method fast
Uri uriPath = FileProvider.getUriForFile(this, getPackageName() + ".sharing.provider", imageFile);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.setClipData(ClipData.newRawUri("", uriPath));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_STREAM, uriPath);
startActivity(Intent.createChooser(intent, "Sharing to..."));
} catch (Throwable e) {
e.printStackTrace();
}
}
If you want to capture a view or layout like RelativeLayout or LinearLayout etc.
Just use the code:
LinearLayout llMain = (LinearLayout) findViewById(R.id.linearlayoutMain);
Bitmap bm = loadBitmapFromView(llMain);
now you can save this bitmap on device storage by :
FileOutputStream outStream = null;
File f=new File(Environment.getExternalStorageDirectory()+"/Screen Shots/");
f.mkdir();
String extStorageDirectory = f.toString();
File file = new File(extStorageDirectory, "my new screen shot");
pathOfImage = file.getAbsolutePath();
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
Toast.makeText(getApplicationContext(), "Saved at "+f.getAbsolutePath(), Toast.LENGTH_LONG).show();
addImageGallery(file);
//mail.setEnabled(true);
flag=true;
} catch (FileNotFoundException e) {e.printStackTrace();}
try {
outStream.flush();
outStream.close();
} catch (IOException e) {e.printStackTrace();}

Android Asynctask and progressDialog

What I would like to do is give my app the ability to download my mp3 of my server. So far I have the download mp3 into a audio file working but it's very finicky and cannot be disturbed in order for it to work properly. That being said I would love to have a progress dialog pop up that cannot be canceled so the user can't interrupt the progress while downloading the file to the folder in the background. After reading it seemed that AsyncTask would be the best way to do this but I cannot get it to work. Below is one of the buttons from my code.
public class music extends Activity {
public static int mProgress = 0;
static String filename;
MediaPlayer buttonclicker;
static Toast msg;
public static int totalSize = 0;
public ProgressDialog dialog;
public static boolean isFinished;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
buttonclicker = MediaPlayer.create(this, R.raw.button );
Button boomFullDownload = (Button) findViewById(R.id.boomfull);
boomFullDownload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonclicker.start();
filename = "boomboom.mp3";
new downloadPumphouseShow().execute(filename);
}
class downloadPumphouseShow extends AsyncTask<String , Void, Void> {
ProgressDialog dialog;
Toast msg;
protected void onPreExecute (){
dialog = new ProgressDialog(context);
msg = Toast.makeText(context, " File Exist ", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
dialog.setMessage("Please Wait Loading");
dialog.setCancelable(false);
dialog.show();
}
}
});
protected void onPostExecute(Void result) {
dialog.hide();
dialog.dismiss();
}
protected Void doInBackground(String... params) {
String filename = params[0];
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("http://lepumphouse.com/media/" + filename );
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File Music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/Pumphouse/Party Cake");
//create a new file, specifying the path, and the filename
if(Music.exists())
msg.show();
else
Music.mkdirs();
//which we want to save the file as.
File file = new File(Music, filename);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int mProgress = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
mProgress += bufferLength;
//this is where you would do something to report the pr0gress, like this maybe
}
//close the output stream when done
// progressDialog.dismiss();
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
So if I stripped out all the code dealing with asynctask it works it's just extremely un-user friendly but the files do download. When I try to add the progress dialog and background task it quits on me. I have a feeling it has to do with the parameters.
protected void onPreExecute() {
dialog=ProgressDialog.show(mContext, "", "Fetching book oversight");
msg = Toast.makeText(context, " File Exist ", Toast.LENGTH_LONG).show;
super.onPreExecute();
}
protected void onPostExecute(Void result) {
if(dialog!=null)
{
dialog.dismiss();
}
}
Try this, a alternate way to show Dialog
Just a quick scan, I don't think you should be calling msg.show(); from the background thread.

Categories

Resources