How to share PDF, XIS, DOC, PNG from URL - java

Here is my code
Glide.with(getContext())
.asBitmap().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
.load(url)
.into(new SimpleTarget<Bitmap>(250, 250) {
#Override
public void onResourceReady(Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
progressBar.setVisibility(View.GONE);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Share");
String path = MediaStore.Images.Media.insertImage(getContext().getContentResolver(), resource, "", null);
Uri screenshotUri = Uri.parse(path);
intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
intent.setType("*/*");
startActivity(Intent.createChooser(intent, "Send to"));
}
#Override
public void onLoadFailed(Drawable errorDrawable) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
super.onLoadFailed(errorDrawable);
}
#Override
public void onLoadStarted(Drawable placeholder) {
progressBar.setVisibility(View.VISIBLE);
Toast.makeText(getContext(), "Sharing", Toast.LENGTH_SHORT).show();
super.onLoadStarted(placeholder);
}
});
I am implementing share option in my Android application using URL. The URL contains all types of files like PDF, PNG, DOC, DOCX, etc. I tried to share PNG file among other apps and it's working fine.
The issue is I cannot able to share PDF and other format files except image. How can I share all the MIME type files?

May this example help you, I used this code for Sending PDF files, you can send mutiple by using array and Intent.ACTION_SEND_MULTIPLE:
public void shareFile(File file) {
Uri uri = FileProvider.getUriForFile(mContext, com.example.app, file);
shareFile(uri);
}
Call shareFile function and pass URI
private void shareFile(Uri uri) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, mContext.getString(R.string.file_with_message));
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("application/pdf");
mContext.startActivity(Intent.createChooser(intent,"Select app to send file");
}

Related

Please Help me to add share Wallpaper code from firebase

I stored url with id in firebase. I am using viewpager2 in xml. I want to share image or want to add share option in that. How can I do this.
public void onApplyImage(int position, Bitmap bitmap) {
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
try {
manager.setBitmap(bitmap);
Toast.makeText(SwiperActivity.this, "Wallpaper successfully set ", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(SwiperActivity.this, "Failed to set as wallpaper", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onShareImage(int position, Bitmap bitmap) {
}
});
Simple way to share is that first set you image to a ImageView and then use the following code to share you image.
ImageView content = (ImageView)mView.findViewById(R.id.imageViewy);
content.setDrawingCacheEnabled(true);
Uri imageUri= Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),
content, "title", "discription"));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));

Connect userId with a unique photo in Firebase

I have an app where it is possible to create an user and this work perfectly and I am happy!
In a simple way, here is a method that adds the user to the Firebase database:
public void addUserInfoToDatabase(){
String user_id = mAuth.getCurrentUser().getUid();
final DatabaseReference the_user_database = FirebaseDatabase.getInstance().getReference().child("UserRegistraion").child(user_id);
Map userAttributes = new HashMap();
userAttributes.put("user_id", user_id);
userAttributes.put("username", userName);
userAttributes.put("name", name);
userAttributes.put("e-mail", email);
the_user_database.setValue(userAttributes);
if (mRegistrationListener != null)
mRegistrationListener.onRegistrationComplete(true); // Assumes success
}
And here is how the table looks when the user is registered:
What I want to do now is that I want the possibility to add a profile picture which belongs to each user: e,g a profile picture, family-picture etc.
The question is: how can i do this in Firebase? I am not asking anyone to do this for me, but just to give me a good tip or provide a guide/video for how to do this.
Thank you.
I usually create a separate activity for setting up a profile photo. Maybe instead of calling onRegistrationComplete call an onCompleteListener after setValue(userAttributes) like this:
the_user_database.setValue(userAttributes).addOnCompleteListener(new OnCompleteListener...){
Intent intent = new Intent(context, AddProfileActivity.class);
startActivity(intent);
In the next activity it could be a simple XML layout with a button and an ImageView.
This code can open your gallery, select an image, and place it in your imageview in the onActivityResult method:
private void selectPhotoFromGallery(){
Log.d(TAG, "selectPhotoFromGallery: started");
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_PICK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK){
if (resultCode == RESULT_OK && data != null){
contentUri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentUri);
profile_photo.setImageBitmap(bitmap);
}catch (IOException e){
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
You would then need a method to upload your image to FirebaseStorage and capture the downloadUrl to add to the desired node. In this case because you are adding to an existing node you call updateChildren() when adding the profile photo. I use a method like this:
private void uploadProfileImage(){
Log.d(TAG, "uploadProfileImage: uploading image....");
if (contentUri != null){
//from gallery
final StorageReference reference = FirebaseStorage.getInstance().getReference().child(currentUserID).child("profile_photo");
reference.putFile(contentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String profilePhotoUri = uri.toString();
DatabaseReference publicUserReference = FirebaseDatabase.getInstance().getReference().child("public_user")
.child(currentUserID);
HashMap hashMap = new HashMap();
hashMap.put("profile_photo", profilePhotoUri);
publicUserReference.updateChildren(hashMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
Intent intent = new Intent(mContext, CompleteProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
});
}
});
}
});
}
}
You would need to adjust this for your specific needs obviously. The thing you are really trying to do is to save an image to Storage and get the http://... string location where it is stored and then insert that information into the same location as the previous information you provided.
I hope this counts as a helpful tip. https://www.youtube.com/watch?v=mPOhnTnLcSY That's a link to a video about uploading images to Firebase storage for more information if you need it. Good luck!

Android save Speech to Text audio

I am trying to create an app that will allow a user to upload an audio file created by Googles speech to text to a server. I have managed to get the URI for the audio file but how do I access it or convert it to a listenable format? I tried to play it back but nothing so far. This is what I have.
My Speech to text
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case REQ_CODE_SPEECH_INPUT: {
Bundle bundle = data.getExtras();
if(resultCode==RESULT_OK && null!= data){
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
vtt.setText(result.get(0));
Uri audioUri = data.getData();
uri.setText(String.valueOf(audioUri));
audioPath = uri.getText().toString();
}
break;
}
}
}
When I tried to play the audioPath variable. Nothing came out. How do I convert it to a listenable format?
Example of a uri that I got
content://com.google.android.googlequicksearchbox.AudioProvider/NoteToSelfOriginalAudio1.amr
Thank you for your help
I found somewhere that I should use content resolver and do something with the inputstream but Im not sure what.
I managed to solve the question.
The easiest way would be to use functions from apache commons IO
audioPath = uri.getText().toString();
finalPath = combinedPath.replaceAll(" ","");
Log.d("Filepath",combinedPath.replaceAll(" ",""));
ContentResolver contentResolver = getContentResolver();
try{
InputStream filestream = contentResolver.openInputStream(audioUri);
File targetFIle = new File(finalPath);
FileUtils.copyInputStreamToFile(filestream,targetFIle);
}catch (IOException e){
e.toString();
}
Button_to_speak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent
= new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to text");
try {
startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT);
}
catch (Exception e) {
Toast
.makeText(MainActivity.this, " " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
}
});

Sharing text with image to instagram using android intent

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

Android: Sharing Bitmap with Intents on other apps

I have a bitmap file that I created using Android Query:
aq = new AQuery(HomeCategoryActivity.this);
aq.ajax(currentUrl,Bitmap.class,0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
if(object != null)
{
bmp = object;
}
}
});
bmp is a globally initialized variable and it gets properly saved by the above code and NOT NULL, I checked.
Now I want to share this bitmap on other apps using this:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(bmp));
startActivity(Intent.createChooser(intent, "Share Product via:"));
This won't work since the code is probably wrong. What changes should I make?
I want to share the image on Fb, insta, etc
Save bitmap to external storage and get path of the bitmap image
then pass the Uri.parse(path)to the intent.
for more information refer to this link http://developer.android.com/training/sharing/send.html
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parseUri(path));
startActivity(Intent.createChooser(intent, "Share Product via:"));

Categories