So i am making app in Android studio(java) and i am using image picker from https://github.com/Dhaval2404/ImagePicker. Is there a way to get result from image picker without using deprecated method
onActivitiyResult() ? I have read https://www.tutorialguruji.com/android/onactivityresult-method-is-deprecated-what-is-the-alternative/ this article but i am not quite sure how to use image picker in this context.
Thanks for any kind of help!
First of all you have to create a Uri (a path from where you want User to select the image), then you can use this Uri to pass to the intent and it will directly go to that Uri. Here, due to Storage Access Changes on Android 10 onwards we can't directly get the path to root directory, so here we pass the uri to get all the images present in External Volume of Device. And in Android 9 below we can directly access Root Directory, so the Uri is different.
binding.imageCamera.setOnClickListener { v ->
Uri uri;
if (isSdk29andUp()){
uri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
Intent intent = new Intent(Intent.ACTION_PICK, uri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pickPhotoLauncher.launch(intent);
}
ActivityResultLauncher<Intent> pickPhotoLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
// Here the data will be Uri.
}
}
});
}
Related
One feature of my app includes the camera. The user takes a picture and the app displays the image.
I start an intent with ACTION_IMAGE_CAPTURE using StartActivityForResult and capture the response with onActivityResult. Usually I can simply call getData() on the intent I receive in onActivityResult and get the content uri for the MediaProvider.
My problem is the following: One one of my test devices, a Huawei ALE-L21, the intent I get in onActivityResult has no data, but instead, it has a parcellable extra. How could I get the users photo from that? Android Studio doesn't tell me the name of the parcellable extra either
Disclaimer: I call getActivity() because I'm using this code in a fragment
This is what I use to get the camera.
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, getResources().getInteger(R.integer.RQ_PERMISSION_WRITE_EXTERNAL_STORAGE));
}
And here's the code in my onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultIntent) {
super.onActivityResult(requestCode, resultCode, resultIntent);
switch (requestCode) {
case 1: //RQ_ImageCapture
case 2: //RQ_ImageSelected
if (resultIntent != null) {
try {
Uri selectedImage = resultIntent.getData();
if(selectedImage != null) {
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
setImageAsBackground(selectedImage, bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
Usually I can simply call getData() on the intent I receive in onActivityResult and get the content uri for the MediaProvider.
Your code will fail on many of them, including all recent Nexus devices. ACTION_IMAGE_CAPTURE is not supposed to return a Uri. Quoting the documentation:
If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field. This is useful for applications that only need a small image. If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri value of EXTRA_OUTPUT.
Since you are not including EXTRA_OUTPUT, you will get a data extra (getData().getExtra("data")) with a thumbnail image.
the intent I get in onActivityResult has no data, but instead, it has a parcellable extra
Given your ACTION_IMAGE_CAPTURE request, that is what you are supposed to get.
If you want a full-size image, include EXTRA_OUTPUT, perhaps pointing to a FileProvider in your app, such as I demonstrate in this sample app. Then, you know the Uri where the photo should go, because you specified that Uri.
Hi guys was wondering if there was a bit of code I could use that would make an app auto install once the download completes?
My app has a download section with in it. I was using Google Drive to handle the downloads. but I am encountering issues with some devices. So I have decided to move away from google
I am now using media fire as my host. My app uses direct download. But it always downloads using the download manager. What I would like it to do is more like how Google Drive works with direct download. Which is it gives me the option to install as soon as download completes.which i have now solved with these few lines of code
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new
File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
is there a way to check download folder before downloading the file. if the file is already there install if not got to web page for download. rather it saying parse error then going to webpage or having multiple downloads of same file.
Thanks in advance as always.
You can get the downloaded Uri after the download complete, so you don't have to specify a file name to save. If you use DownloadManager, below is a simple example.
final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://remotehost/your.apk"));
final long id = downloadManager.enqueue(request);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
Intent installIntent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
installIntent.setDataAndType(downloadManager.getUriForDownloadedFile(id),
"application/vnd.android.package-archive");
} else {
Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(id));
try {
if (cursor != null && cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
String localUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
installIntent.setDataAndType(Uri.parse(localUri), "application/vnd.android.package-archive");
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.sendBroadcast(installIntent);
}
}
};
registerReceiver(broadcastReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
I have a main activity, in which the user is shown a dialogue to pick an image from the gallery or use the camera. The problem is ( I think ) that i'm building against the 6.0 APIs and the permissions are what's messing me up.
When the application passes the Uri (As a string) into a database, the Adapter has to access that database and get the picture and put it into an ImageView.
I get the READ_EXTERNAL_STORAGE permission to access the file in the MainActivity, but I think I also need it in the adapter, but I can't access permissions from in there.
//TL;DR how can I access the internal storage (pictures) from inside of a recyclerview adapter class?
Here's my code:
After I check for permissions, I start the intent to pick the image:
//RESULT_LOAD_IMAGE = 0;
Intent toGal = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(toGal, RESULT_LOAD_IMAGE);
then, inside of the onActivityResult, I get the URI and set a variable to it's string value
boolean request = requestCode == RESULT_LOAD_CAMER || requestCode == RESULT_LOAD_IMAGE;
if (resultCode == Activity.RESULT_OK && request && imageReturnedIntent != null) {
Uri selectedImage = imageReturnedIntent.getData();
picturePath = String.valueOf(selectedImage);
Log.i(TAG, picturePath);
}
And then I store it in a Realm database, and access it from the adapter. I know this is not the problem, because I can log the path that was stored in the db that points to the image just fine.
Here is where I access it inside of the Adapter:
String imgString = Model.getImage(); //This is "/emulated/storage/pathtoimg.jpg"
if (imgString != null) {
Bitmap BM = BitmapFactory.decodeFile(imgString);
ImageView.setImageBitmap(BM);
}
}
But nothing happens. When I try to request permissions from inside the Adapter it says it needs to be an activity so how can I access the internal storage from a recyclerview adapter?
I know that this question has been asked several times before, I am trying to add caption to image shared to instagram using send intent
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM,uri);
shareIntent.putExtra(Intent.EXTRA_TEXT,"YOUR TEXT TO SHARE IN INSTAGRAM");
shareIntent.setPackage("com.instagram.android");
return shareIntent;
Has someone ever managed to make it work?
Is it not supported or has the support been revoked?
There was an official statement from Instagram (mid-2015) announcing that pre-populated captions would no longer be accepted in the iOS and Android apps:
Beginning today, the iOS Hooks and Android Intents will stop accepting captions passed by third party apps. This is a non-breaking change: existing mobile apps that utilize pre-filled captions will continue to be able to use this flow to share media through the Instagram apps, but now Instagram will ignore the caption text. To create a caption for a photo or video shared by a third party app, users will have to enter a caption manually, the same way they already do when sharing content using the Instagram native apps.
Looking at the Instagram documentation for Android, indeed we see that there's no mention of providing the conventional Intent.EXTRA_TEXT string extra in the intent as is customary for other apps. Their sample is limited to only providing a Uri:
// Add the URI to the Intent.
share.putExtra(Intent.EXTRA_STREAM, uri);
// Broadcast the Intent.
startActivity(Intent.createChooser(share, "Share to"));
I'm sorry to say that it simply isn't possible, and we're at the discretion of Facebook in making this decision.
Until it`s not solved by Instagram, I copy the text to the clipboard and instruct the user to paste it
#Override
public void onSingleImageSelected(Uri uri, String tag) {
fileProfileImage = uri.getPath();
compressProfileImage();
imgShareTosocial.setVisibility(View.VISIBLE);
Glide.with(getApplicationContext()).load(uri).into(imgShareTosocial);
}
#SuppressLint("CheckResult")
private void compressProfileImage() {
File file = new File(fileProfileImage);
new Compressor(this)
.compressToFileAsFlowable(file)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<File>() {
#Override
public void accept(File file) throws Exception {
compressProfileImage = file;
String imagePath = compressProfileImage.getAbsolutePath();
tvSelectMedia.setText(imagePath);
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
}
});
}
private void shareToInstagram() {
path = tvSelectMedia.getText().toString().trim();
Intent intent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
if (intent != null) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setPackage("com.instagram.android");
try {
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), path, "Step Up", "Step Up")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
shareIntent.setType("image/jpeg");
startActivity(shareIntent);
} else {
// bring user to the market to download the app.
// or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + "com.instagram.android"));
startActivity(intent);
}
}
I'm with the same problem. I think is not possible at this time.
In https://instagram.com/developer/mobile-sharing/android-intents/ only talk about Intent.EXTRA_STREAM, so i suppose that it's the only available.
Here is my code:
Intent instagramIntent = new Intent(Intent.ACTION_SEND);
instagramIntent.setType("image/*");
File media = new File(mediaPath);
Uri uri = Uri.fromFile(media);
instagramIntent.putExtra(Intent.EXTRA_STREAM, uri);
instagramIntent.setPackage("com.instagram.android");
PackageManager packManager = getPackageManager();
List<ResolveInfo> resolvedInfoList = packManager.queryIntentActivities(instagramIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for(ResolveInfo resolveInfo: resolvedInfoList){
if(resolveInfo.activityInfo.packageName.startsWith("com.instagram.android")){
instagramIntent.setClassName(
resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name );
resolved = true;
break;
}
}
if(resolved){
startActivity(instagramIntent);
}else{
Toast.makeText(PromocionarMain.this, "Instagram App is not installed", Toast.LENGTH_LONG).show();
}
Instagram have stopped accepting pre-populated capitions to increase the quality of content in the system. See this post.
http://developers.instagram.com/post/125972775561/removing-pre-filled-captions-from-mobile-sharing
I am making an android album app where I can create an album and add photos and delete photos from the album. Adding a photo is a bit tricky where I need a photo filename with a file path. This was very easy using JFileChooser in java but this is android and I have no clue on getting the filename and file path. Is there any thing in the android api where I can get the same functionality as the JFileChooser.
I am looking for a solution to this problem either using a file chooser of some sort or an entire to new approach. Any help is appreciated..
Or is there any other approach I can implement to add a photo...
You may use Intent.ACTION_PICK to invoke an image picker. This intent may be caught by the default gallery app, or some other app installed on the device.
private static final int REQUEST_PICKER = 1;
private void invokePicker() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Complete action using"), REQUEST_PICKER);
}
Then receive the result on onActivityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
if (requestCode == PICK_FROM_FILE) {
// Get Uri of the file selected,
Uri theImageUri = data.getData();
// Or if you want a Bitmap,
Bitmap theBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), theImageUri);
}
}
Edited:
Though in this way you don't need a real file path, you can get it from MediaStore if you need.