How to add a new directory to android gallery app - java

So I am trying to have a directory added to the stock android gallery app, and I can't get it to work. I tried the Stock android approach for that, I have also tried the way that is supplied via AOSP and neither have worked. How might I create a new directory, take a new picture and add it to the gallery. I have the photo saving and everything wokring it's just getting it to display in the Gallery app that isn't working
The way google says to add photos to the gallery is the following way....
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
I personally have it set up for
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
Config.context.sendBroadcast(mediaScanIntent);
}
where Config.context is initialized in MainActivity to getApplicationContext();

So I changed my function to the following
private void galleryAddPic(String Location) {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(Location);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
And to call the function
galleryAddPic(image.getAbsolutePath());
where image is a File
Not the way I had it
galleryAddPic("file:"+image.getAbsolutePath());

Related

Take a picture without opening the Camera application

I currently have an application with a button that takes a photo. However, when I click the button the default camera application opens, then you manually have to take a photo. How do I get the camera application to not open and just take a picture automatically and save it just by pressing the button in my application? I would like to press the button that I created and it takes a photo and saves it automatically.
MainActivity.java
public class MainActivity extends AppCompatActivity {
//for taking photos
static final int REQUEST_IMAGE_CAPTURE = 1;
String currentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onResume(){
super.onResume();
}
//button to start image capturing process
public void startImageCapture(View view){
dispatchTakePictureIntent();
galleryAddPic();
}
//method for taking a photo
public void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Ensure that there is a camera activity to handle the intent
if(takePictureIntent.resolveActivity(getPackageManager()) != null){
//create the file where the photo should go
File photoFile = null;
try{
photoFile = createImageFile();
}catch(IOException e){
Log.i("ERROR","Error in trying to create file for image");
}
//continue only if the file was successfully created
if (photoFile != null){
Uri photoURI = FileProvider.getUriForFile(this,"com.example.MyProject.provider",photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
startActivityForResult(takePictureIntent,REQUEST_IMAGE_CAPTURE);
}
}
}
private File createImageFile() throws IOException{
//Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, //prefix
".jpg", //suffix
storageDir //directory
);
//Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void galleryAddPic(){
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
For me the easiest solution is using camera view (your own wrapper of Camera2 API or existing CameraView) inside your application and making it invisible or placing some view above it, if you want to hide it.
CameraView API is simple (CameraView Getting Started): just add view into layout, set LifecycleOwner, set callback on taking picture and call camera.takePicture(), when you need to take picture.

Save drawables in local storage as cache and then read them for a Share_Intent?

I have drawables in my project that i have declared as seperate resource array
public Integer[] mThumbIds = {
R.drawable.ic_bl1,
R.drawable.ic_bl2,
R.drawable.ic_bl3,
R.drawable.ic_bl4,
R.drawable.ic_bl5,
R.drawable.ic_ca1,
R.drawable.ic_ca2,
R.drawable.ic_ch}
I want to save them all in a temp folder on local storage of android(not SD Card)so that I can retrieve them later and send them via a share intent.I have code for share Intent completed
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/*");
sharingIntent.putExtra(Intent.EXTRA_STREAM, path);
// sharingIntent.setPackage("com.facebook.orca");
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent chooserIntent = Intent.createChooser(sharingIntent, "Send Via");
chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sContext.startActivity(chooserIntent);
// sContext.startActivity(sharingIntent);
}
});
I need to pass a Uri of a particular file to be sent,and best way to get it is through saving images in local storage and then retrieving there Uri.I know how to save a single image in cache and then retrieving it.
I can't figure out how to save a list of drawables in a particular folder on local storage and then retrieving there Uris for a use in share intent later.
You could use this code.
But add read and write storage permission.
public void onClick(View view) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/png");
ImageView imageView = (ImageView) view;
Drawable mDrawable = imageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();
String path = MediaStore.Images.Media.insertImage(mContext.getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Content!!"));
}

Permission Denial: MediaDocumentsProvider

I am getting the following exception when trying to display a URI. I think it occurs after my activity is stopped and I try to access a viable URI again. There are other questions addressing this problem but I am very confused as to how to apply any solutions to my code since my takePhotoIntent allows for a picture to either be taken or chosen from gallery (found below).
Unable to open content: content://com.android.providers.media.documents/document/image%3A49688
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaDocumentsProvider uri
content://com.android.providers.media.documents/document/image%3A49688 from pid=821, uid=10238 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()
My createImageFile and my takePhotoIntent:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
for(int i = 0; i < 4; i++) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
outputFileUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Log.w("error","IOException");
}catch (NullPointerException nullEx) {
Log.w("error","NullPointerException");
}
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
if(id.equals(HAPPY_ID))
startActivityForResult(chooserIntent, REQUEST_HAPPY_PHOTO);
if(id.equals(SURPRISED_ID))
startActivityForResult(chooserIntent, REQUEST_SURPRISED_PHOTO);
if(id.equals(AFRAID_ID))
startActivityForResult(chooserIntent, REQUEST_AFRAID_PHOTO);
if(id.equals(UPSET_ID))
startActivityForResult(chooserIntent, REQUEST_UPSET_PHOTO);
if(id.equals(SAD_ID))
startActivityForResult(chooserIntent, REQUEST_SAD_PHOTO);
}
}
}
Per the Storage Access Framework client documentation:
Use ACTION_GET_CONTENT if you want your app to simply read/import data. With this approach, the app imports a copy of the data, such as an image file.
Use ACTION_OPEN_DOCUMENT if you want your app to have long term, persistent access to documents owned by a document provider. An example would be a photo-editing app that lets users edit images stored in a document provider.
As you are using ACTION_GET_CONTENT, your access to the Uri ends when the component is destroyed (unless you pass the Uri to a new component). You must make a copy of the file from the Uri if you'd like to continue to access it beyond the lifetime of your component or switch to ACTION_OPEN_DOCUMENT and persist permissions (possible only with document Uris).

Android - Intent Sharing

How to detect from which (any) external app(or packagname) data was shared:
Via sharing an image/data (intent) from another app to my app(activity),
private void shareImage() {
Intent share = new Intent(Intent.ACTION_SEND);
// If you want to share a png image only, you can do:
// setType("image/png"); OR for jpeg: setType("image/jpeg");
share.setType("image/*");
// Make sure you put example png image named myImage.png in your
// directory
String imagePath = Environment.getExternalStorageDirectory()
+ "/myImage.png";
File imageFileToShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileToShare);
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image!"));
}

How to use this code to save the images inside my android camera app?

I built my own camera so it could be launched from inside my other android app, i want to save the images inside this app and not in the default gallery, i was using getExternalFilesDir() because i wanna keep the data just inside my app. But it is not working quite right, does anybody know what i have to change?? I do have the permission in my manifest.
My phone is an HTC phone
private void dispatchTakePictureIntent(int actionCode) {
imageURI = getExternalFilesDir(null) + File.separator
+ System.currentTimeMillis() + ".jpg";
File mFile = new File(getFilesDir(), "newImage.jpg");
if(!mFile.exists()) {
try{
mFile.createNewFile();
} catch (Exception e){
return;
}
}
//Uri iURI = Uri.parse(imageURI);
Log.v("camera", mFile.toString()); // Debugging statement
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
startActivityForResult(takePictureIntent, actionCode);
}
Here is the code that i am using to do it.
To hide the images from gallery you should create .nomedia file in the folder with images, or create your own camera app.

Categories