I have the URL to an image and I want to give the user the ability to share this images to another apps. So I am using this method:
public void share() {
if (mListener!=null){
URI uri = null;
try {
URL url = new URL(mFile.getUrl()); //Some instantiated URL object
uri = url.toURI();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));
} catch (MalformedURLException | URISyntaxException e) {
Log.e("Sharing image", e.getMessage());
}
}
}
When I try to share to WhatsApp I get "Sharing failed, please try again" and for Telegram I get "Unsupported content" it doesn't work with any of the options I get to choose from.
You can use share text intent using the following methods.
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL");
i.putExtra(Intent.EXTRA_TEXT, uri.toString());
startActivity(Intent.createChooser(i, "Share URL"));
Or with the ShareCompat from support library.
ShareCompat.IntentBuilder.from(activity)
.setType("text/plain")
.setChooserTitle("Share URL")
.setText(uri.toString())
.startChooser();
I managed to solve my own problem by using AsyncTask to convert the URL to an BitMap and then sharing to other apps. This is the code that I used:
public void share() {
if (mListener!=null){
new LongOperation().execute();
progress = new ProgressDialog(getActivity());
progress.setTitle(getActivity().getResources().getString(R.string.please_wait));
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Intent intent = new Intent(Intent.ACTION_SEND);
//intent.putExtra(Intent.EXTRA_TEXT, "Hey view/download this image");
String path = Images.Media.insertImage(getActivity().getContentResolver(), getBitmapFromURL(mFile.getUrl()), "", null);
Uri screenshotUri = Uri.parse(path);
intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share image via..."));
progress.cancel();
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
Related
I want to share image and text to another app but i'm getting file format not supported when i'm using this code please help...
Uri picUri = Uri.parse("http://www.planwallpaper.com/static/images/image-slider-2.jpg");
Intent shareIntent = new Intent();
shareIntent.setAction(android.content.Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hi There...");
shareIntent.putExtra(android.content.Intent.EXTRA_STREAM, picUri);
shareIntent.setType("*/*");
startActivity(Intent.createChooser(shareIntent, "Share Image...."));
try this
private class myTask extends AsyncTask<Void, Void, Bitmap> {
protected Bitmap doInBackground(Void... params) {
Bitmap myBitmap=null;
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
// Log exception
}
return myBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
//do stuff
}
}
Bitmap returned_bitmap = new myTask().execute().get()
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "download this image");
String bitmapPath = Images.Media.insertImage(getContentResolver(), returned_bitmap,"title", null);
Uri bitmapUri = Uri.parse(bitmapPath);
intent.putExtra(Intent.EXTRA_STREAM, bitmapUri);
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share image via..."));
The documentation for EXTRA_STREAM says that the Uri needs to have a content scheme. file usually also works, at least on Android 6.0 and older. Few apps will expect an http URL.
I am trying to open PDF files from external URL. The code is the next:
private void cargaPdf(Uri url){
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(url,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
}
I have installed adobe and google PDF viewer but when i push the buttom that calls "cargaPdf(Uri url)" function with this url(as you can see is a pdf file):
Uri.parse(https://dl.dropboxusercontent.com/s/oulzgpgnq2ca1ly/KorfbalSpa.pdf?dl=0);
It appears in the screen in spanish "Open File Ninguna aplicacion puede realizar esta accion" or english "Open file No apps can perform this action". What happen?
Edit 1: Ok, now i know that i have to download the file to see it, so, i did this code in the activity:
public void cargaDescripcion(View view){
Log.d("CargaDescripcion", "Antes del directorio");
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "Mypdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
Log.d("CargaDescripcion", "File creado");
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile(deporte.getUrlDescEs(), file);
Log.d("CargaDescripcion", "Despues de descargarlo");
showPdf();
//folder.delete();
}
public void showPdf()
{
Log.d("showPdf", "Entramos en show pdf");
File file = new File(Environment.getExternalStorageDirectory()+"/Mypdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
//file.delete();
}
And this class for download the pdf:
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I got it from here Opening pdf file from server using android intent
Edit 2: Now this is the code which download and shows the file:
public void cargaDescripcion(View view){
download(deporte.getUrlDescEs());
showPdf();
//folder.delete();
}
public void download(String url)
{
new DownloadFile().execute(url, "read.pdf");
}
public void showPdf()
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Mypdf/" + "read.pdf"); // -> filename = maven.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(SelectedSportActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
private class DownloadFile extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> url del archivo
String fileName = strings[1]; // -> nombre del archivo.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "Mypdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
Downloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
However, the file system is not created by app and file is not downloaded before the app arrives to the next point, that it is "show". So, the file does not exists when the app looks for it.
Edit 3: to SOLVE the show problem i used onPostExecute of asynctask method:
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
showPdf();
}
Use this code, this works for me for local file.
resumePdfFile is file path, where your file is saved.
private void openPDF(String resumePdfFile) {
//file should contain path of pdf file
Uri path = Uri.fromFile(resumePdfFile);
Log.e("create pdf uri path==>", "" + path);
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(),
"There is no any PDF Viewer",
Toast.LENGTH_SHORT).show();
finish();
}
}
You can view or download the pdf files by two ways i.e by opening it in device default browser or in the webview by embedding it in your app.
To open the pdf in browser,
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);
To open in webview,
Webview webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(pdf_url);
When opening a document with the Office app (both Word, Excel) in Android by calling startActivity(intent), Office for Android displays the previously shown document whereas Google doc shows the correct document.
How can I solve this issue?
The documents are created by Word 2016 and Excel 2016 (Windows) and can be opened from Google Drive without any error. I set
intent.setDataAndType(uri, "application/vnd.ms-excel"); and intent.setDataAndType(uri, "application/msword"); in my code.
Following are code in test.
private class AsyncXlsLoader extends AsyncTask<String, Void, Integer> {
private final ProgressDialog dialog = new ProgressDialog(getContext());
private File tempFile;
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
dialog.dismiss();
if (result == 0) {
try {
Intent target = new Intent(Intent.ACTION_VIEW);
Intent intent = Intent.createChooser(target, "Open File");
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Uri uri = FileProvider.getUriForFile(getContext(), "com.mydomain.fileprovider", tempFile);
intent.setDataAndType(uri, "application/vnd.ms-excel");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getContext(), e.toString(),
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), " No data!",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Downloading " + xlsfile + "...");
dialog.show();
}
#Override
protected Integer doInBackground(String... params) {
Integer result = new Integer(0);
URL u;
xlsDir = getContext().getFilesDir();
try{
u = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.connect();
// Read the stream
tempFile = new File(xlsDir + "/xlsxfiles/", tempXlsName);
DeleteFile(tempFile, tempXlsName);
if (tempFile.getParentFile().mkdirs()) {
tempFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(tempFile);
InputStream is = u.openStream();
byte[] b = new byte[1024];
int length = 0;
while ((length = is.read(b)) != -1) {
fos.write(b,0, length);
}
fos.flush();
fos.close();
is.close();
conn.disconnect();
return 0;
}
catch(MalformedURLException nameOfTheException){
u = null;
return -1;
}
catch (Throwable t){
t.printStackTrace();
return -1;
}
}
} // End AsyncXlsLoader
I am developing an android application and i need to share the image on button click.But i am getting Image URl only. So, how can i share the image???
And i am getting empty attachment if i give image URL to the intent.
my code is:
sharebut =(Button)findViewById(R.id.sharebut);
sharebut.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
String screenshotUri = flag;
sharingIntent.setType("image/*");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
}
});
Add the path where your image is located in sd card in Uri.parse("file:///"+ yourImagePath)
Use :
String path= "/Downloads/image1.jpg"; //Add your path here
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///"+ path));
Please try this solution for share image via email from URL.
String path = "";
URL url;
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setClassName("com.google.android.gm",
"com.google.android.gm.ComposeActivityGmail");
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, description);
try {
url = new URL(thumnbnailURL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap immutableBpm = BitmapFactory.decodeStream(input);
Bitmap mutableBitmap = immutableBpm.copy(
Bitmap.Config.ARGB_8888, true);
View view = new View(VideoDetailsActivity.this);
view.draw(new Canvas(mutableBitmap));
path = Images.Media.insertImage(getContentResolver(),
mutableBitmap, "Nur", null);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Uri uri = Uri.parse(path);
intent.setType("application/image");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(intent);
I found the solution.. :)
Just created a file and share the content in imageview.
sharebut =(Button)findViewById(R.id.sharebut);
sharebut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
imgflag.buildDrawingCache();
Bitmap bmap = imgflag.getDrawingCache();
OutputStream out = null;
String path =Environment.getExternalStorageDirectory().toString();
File file = new File(path, "test.png");
try {
file.createNewFile();
out = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share Your Image"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I am trying to display pdf file in android webview by calling amazon url. But it only shows white screen.Nothing to load.
When i use url other then amazon it shows pdf file in webview.
I have also tried this:
http://docs.google.com/gview?embedded=true&url=" + MYURL
I have also tried under write url as well: And works well.
http://www.durgasoft.com/Android%20Interview%20Questions.pdf
If any one have any suggestion please guide me.
Here is my code for your reference:
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
String url = Common.getPdfFromAmazon("52f3761d290c4.pdf");
webView.loadUrl(url);
Android Menifest.xml also give Internet Permission:
**<uses-permission android:name="android.permission.INTERNET" />**
i can also try this "http://docs.google.com/gview?embedded=true&url=" + url ;
Thank you.
For displaying a PDF from amazon web service you need to first download and store the PDF to your device and then open it through PDF reader/viewer application available on your device.
1>> Call DownloadFileAsync() to invoke download process and pass your amazon web service url.
new DownloadFileAsync().execute(url);
2>> Do the download PDF process in AsyncTask.
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(final String... aurl) {
try {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File dir = new File(extStorageDirectory, "pdf");
if(dir.exists()==false) {
dir.mkdirs();
}
File directory = new File(dir, "original.pdf");
try {
if(!directory.exists())
directory.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
int lenghtOfFile = conexion.getContentLength();
conexion.connect();
conexion.setReadTimeout(10000);
conexion.setConnectTimeout(15000); // millis
FileOutputStream f = new FileOutputStream(directory);
InputStream in = conexion.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.flush();
f.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused) {
}
}
3>> Call showPdfFromSdCard() after downloading pdf.
public static void showPdfFromSdCard(Context ctx) {
File file = new File(Environment.getExternalStorageDirectory() + "/pdf/original.pdf");
PackageManager packageManager = ctx.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
ctx.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(ctx,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
4>> Call deletePdfFromSdcard() in your onResume()
public static void deletePdfFromSdcard(){
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/original.pdf");
boolean pdfDelete = file.delete();
}
You need to add the internet permission to your manifest file outside of the application tag.
<uses-permission android:name="android.permission.INTERNET" />
after 2 day research no solution find for that so i try to first download PDF file from Amazon web service and store into the SD-Card then open PDF File Here My Code
Note:- This solution is only try for Show PDF in Web view From Amazon web Service.
from other web service try this Code:-
WebView webview=(WebView)findviewbyid(R.id.Webview);
String MyURL= "this is your PDF URL";
String url = "http://docs.google.com/gview?embedded=true&url=" + MyURL;
Log.i(TAG, "Opening PDF: " + url);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
----------------------------------------------------------------------------------------------> For Amazon Web Service Please Try This code
1>> Download PDF from Amazon WebService
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2>> Show PDF From SD-Card
public static void showPdfFromSdCard(Context ctx)
{
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/MyPdf.pdf");
PackageManager packageManager = ctx.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
ctx.startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(ctx,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
After Download PDF showPdfFromSdCard Method called.
After show PDF you Delete PDF file From SD-card
Here Code for Delete PDF From SD-Card
public static void deletePdfFromSdcard(){
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/MyPdf.pdf");
boolean pdfDelete = file.delete();
}
I will do some modification in #Monika Moon code,
if you don't want to save the File in the device, the process explained above is too long as well as required FileProvider to open the pdf in external pdf viewer.
so for the better solution please follow the below steps.
Step 1:
please add this library to your gradle file.
AndroidPdfViewer
Step 2:
add this in your XML view->
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Step 3:
PDFView pdfView;
InputStream inputStream;
pdfView=findViewById(R.id.pdfView);
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
if (mProgressDialog!=null)
{
Utils.cancelProgressDialog(mProgressDialog);
}
mProgressDialog = Utils.showProgressDialog(DocumentViewActivity.this);
super.onPreExecute();
}
#Override
protected String doInBackground(final String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
conexion.setReadTimeout(20000);
conexion.setConnectTimeout(25000); // millis
inputStream = conexion.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused) {
if (inputStream != null) {
pdfView.fromStream(inputStream)
.defaultPage(0)
.password(null)
.scrollHandle(null)
.enableAntialiasing(true)
.scrollHandle(new DefaultScrollHandle(DocumentViewActivity.this))
.spacing(0)
.onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
Utils.cancelProgressDialog(mProgressDialog);
}
})
.load();
}else {
Utils.cancelProgressDialog(mProgressDialog);
}
}
}
#Override
protected void onDestroy() {
if (inputStream!=null)
{
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
Final Step : call new DownloadFileAsync().execute(url);