After using this code:
public void getContent() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(intent, REQUEST_CODE_GET_CONTENT);
} catch (ActivityNotFoundException e) {
// No compatible file manager was found.
Toast.makeText(this, R.string.no_filemanager_installed,
Toast.LENGTH_SHORT).show();
}
}
the phone pops up a window where you can choose between audio or images file. I just want the audio and I don't want that the user can choose the image files. how can I do to not show this window and automatically go to audio selection?
Try intent.setType("audio/*");
Related
I am developing an app for filling pdf forms, I am saving the pdf to the internal storage and then sharing it using the intent ACTION_CREATE_DOCUMENT. This intent returns a URI which i then copy my local pdf into.
All this works fine however the intent opens a file explorer popup so that the user can choose where to save the pdf, and here in lies the problem, when the user presses SAVE; the app creates a 0b file in that location (as it should), but then it reopens the file explorer prompting the user to SAVE again, this happens two or three times and then it finally close for real at which point the pdf data overwrites the latest of the now numerous 0b files.
public int WRITE_REQUEST_CODE=45;
...
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void buttonExport(View view) {
Toast.makeText(this, "Exporting - This will take around 1min", Toast.LENGTH_LONG).show();
// Template of PDF with acrofields (template.pdf).
// TRY to open the pdf stored in the raw res directory
// then convert it to a file object by copying it
try {
//
InputStream inputStream =null;
if (template.equals("crfminortemplate")){
inputStream = getResources().openRawResource(R.raw.crfminorpdftemplat);
}
else if (template.equals("crfmajortemplate")){
inputStream = getResources().openRawResource(R.raw.crfmajorpdftemplat);
}
File tempFile = new File(getFilesDir(),template);
//
copyFile(inputStream, new FileOutputStream(tempFile));
// Now Questions res is tempFile ..
} catch (IOException e) {
throw new RuntimeException("Can't create temp file ", e);
}
try {
PDFManipulation.fillPDF(view, template, fileName, Answers);
} catch (IOException e) {
e.printStackTrace();
}
catch (NullPointerException e)
{
e.printStackTrace();
}
Toast.makeText(this, "Export Complete - save to drive or email", Toast.LENGTH_LONG).show();
sharePDF(getFilesDir()+"/"+fileName+".pdf");
}
private void sharePDF(String PDFPPath) {
Uri path = FileProvider.getUriForFile(this, "com.example.cst_app_v3", new File(getFilesDir(),fileName+".pdf"));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Sent from CST App Android " + PDFPPath);
shareIntent.putExtra(Intent.EXTRA_STREAM, path);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setType("application/pdf");
startActivityForResult(shareIntent,0);
Intent saveIntent = new Intent();
saveIntent.setAction(Intent.ACTION_CREATE_DOCUMENT);
saveIntent.putExtra(Intent.EXTRA_TITLE,fileName+".pdf");
saveIntent.addCategory(Intent.CATEGORY_OPENABLE);
saveIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
saveIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
saveIntent.setType("application/pdf");
startActivityForResult(saveIntent,WRITE_REQUEST_CODE);
Intent chooserIntent = Intent.createChooser(shareIntent, "Share or Save ...");
Intent[]arrayofintent = {saveIntent};
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,arrayofintent);
startActivityForResult(chooserIntent,0);
startActivity(chooserIntent);
Log.d("Alert",path.getAuthority()+" "+ path.getPath());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK && requestCode == WRITE_REQUEST_CODE) {
//DO THE COPY PASTE FROM LOCAL to THE URI data
}
}
Again
I want the user to start the save intent and have the file selector popup once let the user name the file and choose the save location, press save and then return to my the my app where the pdf is copied to the location they specified
if anyone knows/has experienced this issue or thinks they know what might be happening it would be great to hear from you.
Every time you call startActivityForResult or startActivity it will start a new Activity.
So I count 4 of these in your example code but with only 2 calls that will actually return a result that would cause a file to be written.
To fix this just remove all the startActivityForResult or startActivity EXCEPT for the third one which you change to startActivityForResult(chooserIntent,WRITE_REQUEST_CODE);
This works (was tested) BUT provides a very bad UI experience as you have to know to select the Files App to save the document.
It would be much better to split these to different types of action in to separate menu items, Buttons, Floating Action Buttons, or however you getting the user to "Share or Save" as you can provide a better UI than the Intent chooser.
I want to click my music icon and let the user decide which music player they want to use, if google play music or another one they have installed
so far I have done this but it just launches the default google play music app
try {
Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_MUSIC);
startActivity(intent);
} catch (Exception e) {
Log.d(TAG, "Exception for launching music player "+e);
}
Instead I was searching in all SO for this and cant find how to list all music players , select one and open it, any ideas ?
This is what I want to do
You can set data type for your Intent:
public void openMusicPlayerChooser(File musicFile) {
if (Build.VERSION.SDK_INT >= 24) {
try {
Method method = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
method.invoke(null);
} catch (Exception e) {
e.printStackTrace();
}
}
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(musicFile), "audio/*");
startActivity(intent);
}
This works for me
Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_MUSIC);
startActivity(intent);
I'm trying to make this program that when the user clicks a button, a message is sent to a whatsapp number
Here is the code in the onClick method
Uri uri = Uri.parse("smsto:" + "xxxxxxxxxx"); //xxx.. is the mobile number
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra(Intent.EXTRA_TEXT, "Check");
i.setType("text/plain");
i.setPackage("com.whatsapp");
startActivity(Intent.createChooser(i, ""));
It shows that there are no apps that can perform this action. Why?
I removed
i.setType("text/plain");
And it works. But the text "Check" is not sent. How to do that if this is not the way.
Your format is slightly different from the example given on the WhatsApp FAQ, so I would modify to match.
From this page:
Like most social apps on Android, WhatsApp listens to intents to share media and text. Simply create an intent to share text, for example, and WhatsApp will be displayed by the system picker:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);
However, if you prefer to share directly to WhatsApp and bypass the system picker, you can do so by using setPackage in your intent:
sendIntent.setPackage("com.whatsapp");
This would simply be set right before you call startActivity(sendIntent);
Try this code to send ON whatsapp
public void SendWhatsapp(View view) {
PackageManager pm=getPackageManager();
try {
Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.setType("text/plain");
String text = "YOUR TEXT HERE";
PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
//Check if package exists or not. If not then code
//in catch block will be called
waIntent.setPackage("com.whatsapp");
waIntent.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(waIntent, "Share with"));
} catch (NameNotFoundException e) {
Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
.show();
}
}
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've searched for a while on the internet but I didnt find a solution!
In my project I put a PDF file inside the drawable folder (I dont know where else to put it, honestly). That PDF is a menĂ¹ that shows the user all the food he can find in that restaurant.
There is a button that enables the user to open that PDF file. By clicking over it I receive a error message. More or less it says that the App cant file my file: "Impossibile to open menuristorante.pdf".
I created a method to open that file and this is the code I wrote:
public void openMenuRistorante(View view)
{
File pdfFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/menuristorante.pdf");
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(this, "Nessuna Applicazione per leggere i pdf", Toast.LENGTH_SHORT).show();
}
}
Probably I am wrong putting my file in the wrong directory.. But where have I to put it? Keep in mind that my PDF file must be already into the app, so it must be inside the phone when the user installs this App.
Thanks
Put the PDF file in the assets folder and try using the following code:
Uri file= Uri.parse("file:///android_asset/mypdf.pdf");
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(file.toString()));
try {
Intent i;
i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(file,mimeType);
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(this,
"No Application Available to view this file type",
Toast.LENGTH_SHORT).show();
}
I'm doing a similar thing in my app, I have my files though in the download folder of my mobile in a sub-folder called "Documents", I guess you could do the same, it's better than keeping it in drawable. here's the code I use :
try {
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/Documents/" + fileName);
Intent intent = new Intent("com.adobe.reader");
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Documents.this, "Erreur d'ouverture du fichier", Toast.LENGTH_LONG).show();
}