How to open PDF file directly from URL in app chooser - android

I need to open a PDF file which I get from URL from JSON.
This URL does not contain file extension at the end of URL. I tried something like this:
final String pdfUrl = dataUrl.replace("data", "file") + "/x?filefield=" + tf.getFieldName() + "&context=\"" + dataItemIdModOne + "\"&skipcache=1";
SharedPreferences sharedPrefs = getActivity().getSharedPreferences(Constants.userDetails, MODE_PRIVATE);
String username = sharedPrefs.getString(Constants.user, "");
String password = sharedPrefs.getString(Constants.pass, "");
String userPassword = username + ":" + password;
final String basicAuth = "Basic " + new String(new Base64().encode(userPassword.getBytes()));
final Map<String, String> extraHeaders = new HashMap<>();
extraHeaders.put("Authorization", basicAuth);
pdfIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse(pdfUrl);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(uri,"*/*");
Bundle bundle = new Bundle();
bundle.putString("Authorization", basicAuth);
target.putExtra(Browser.EXTRA_HEADERS, bundle);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "Please install PDF app", Toast.LENGTH_SHORT).show();
}
}
});
I just need to present to a user an app chooser so he/she will choose with witch app to open a file, or at best, just to directly open available PDF reader on his/her device.
With this implementation, I get the app chooser, and when I try to open a file it loads, but at the end it says that it can not be opened.
So the drill with this URL is that when a URL is called it redirects to another URL which contain the PDF file itself. But I cannot see that second URL. Also when I paste the URL in browser it asks for username and password (that's why I need Basic auth).
Thanks in advance.

Few, if any, PDF viewers will support http/https for their ACTION_VIEW activities. Virtually none of them will support random Intent extras, such as EXTRA_HEADERS.
Download the PDF yourself, using your favorite HTTP client API (e.g., HttpUrlConnection, OkHttp). Then, use ACTION_VIEW to view your downloaded PDF.

Related

Display PDF from uri in Android

i'm getting a pdf file from an api, and i got something like that http://x/docs/document1
In my android project, i have like this:
try{
Android.Content.Intent activity = new Android.Content.Intent(this, typeof(WebViewPDF));
activity.AddFlags(Android.Content.ActivityFlags.GrantReadUriPermission);
activity.AddFlags(Android.Content.ActivityFlags.NoHistory);
string uriAndroid = "http://x/docs/document1";
activity.PutExtra("url", JsonConvert.SerializeObject(uriAndroid));
StartActivity(activity);
}catch (Exception){
...
}
The main problem is, i cannot modify the api, so the endpoint is http://x/docs/document1, but if i try another uri, with the .pdf extension, for example https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf it works fine.
I don't know if i need to get that info from the API in a different way,
How can i show the pdf in the webView or external app without download first the doc?
The solution was download first and then open from local.
void PrintPdf(Uri uri)
{
var webClient = new WebClient();
webClient.Proxy = WebRequest.DefaultWebProxy;
webClient.Credentials = new NetworkCredential("UserName", "Pass");
webClient.Encoding = Encoding.UTF8;
var bytes = webClient.DownloadData(uri);
var text = bytes; // get the downloaded text
string localFilename = "NameforPdf.PDF";
string localPath = System.IO.Path.Combine(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).ToString(), localFilename);
File.WriteAllBytes(localPath, text); // writes to local storage
bool exists = File.Exists(localPath);
if (exists)
{
Java.IO.File file = new Java.IO.File(localPath);
file.SetReadable(true);
//That's the important part, notice the content://
Android.Net.Uri uriLocal = Android.Net.Uri.Parse("content://" + localPath);
Intent intent = new Intent(Intent.ActionView);
intent.SetFlags(ActivityFlags.NewTask);
intent.SetDataAndType(uriLocal, "application/pdf");
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
try
{
StartActivity(intent);
}
catch (Exception)
{
Toast.MakeText(Xamarin.Forms.Forms.Context, "pdf reader not installed", ToastLength.Short).Show();
}
}
}

Android.Net.Uri change caching time

How can I change caching time? I receive a notification when the PDF file is updated on the server. I get the same link, but with another (previous) document. Since URL hashes the previous document, it opens the old one, not the updated one.
Android.Net.Uri uri = Android.Net.Uri.Parse(url);
Intent browserIntent = new Intent(Intent.ActionView, uri);
try {
context.StartActivity(browserIntent);
}
catch (ActivityNotFoundException e) {
Console.WriteLine(e);
Toast.MakeText(context, "Install PDF reader", ToastLength.Short);
}
My URL doesn't change, however, pdf file changes.
I solved my problem, I just changed the URL. And now every URL to the pdf file is unique and not cached.
url = url.Replace(" ", "%20");
url = $"{url}?random_number={new Date().Time}";

Unable to open online streaming PDF in browser

How to open a online stream assets in android.
I had used Intent, but the file gets downloaded and not getting opened in browser.
var uri = Android.Net.Uri.Parse(Url);
Intent intent = new Intent(Intent.ActionView, uri);
StartActivity(intent);
Don't want to use Web view. Any help ?
How to open a online stream assets in android.
You could using google doc service to achieve this function, it just need you
to modify your Url like this :
string Url = "https://docs.google.com/gview?embedded=true&url=" + strPdf;
//Eg :string Url = "https://docs.google.com/gview?embedded=true&url=" + "https://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
var uri = Android.Net.Uri.Parse(Url);

Image url start with https not downloading android

I'm downloading image using url like below,
final String url = article.image.url;
String parentFolder = ""+article.category_id;
final String fileName = ""+article.image.id;
FileManager fileManager = BDevice.getFileManager(mContext);
final File file = BDevice.getFileManager(mContext).getFile(""+article.category_id, parentFolder, fileName);
Uri uri = null;
if (fileManager.isFileExists(file.getAbsolutePath())) {
uri = Uri.fromFile(file);
} else {
if (url != null) {
uri = Uri.parse(url);
}
}
holder.image.setImageURI(uri);
But this is working for this url "https://citylanedev.blob.core.windows.net/citylane/2016/10/Pharmacie_Icon.png"
and not working for this url "https://dev.citylaneapp.com/wp-content/uploads/2016/09/france-mont-saint-michel-2.jpg". After remove 's' from the second url like "http://dev.citylaneapp.com/wp-content/uploads/2016/09/france-mont-saint-michel-2.jpg" its working fine. But i dnt want to remove 's' from the url. I want to download image from the second url. So could you please suggest me any idea to do this?
when I try to open the urls in the browser, the second one
gives that warning, mostly it's a server issue that the server claims it's secured but probably it's SSL Certificates aren't installed, you should contact the server admin.

Android Intent with Gallery application to display images with a File ContentProvider

I implemened a file ContentProvider to access a file server on a wifi network through http urls.
What I am trying to do is to launch the Android Gallery app with a particular intent and uri to display image files that are in a particular directory on my file server.
I am able to succeed if I launch the Gallery app with a single uri to display one image through this code :
Intent lance = new Intent();
lance.setAction(Intent.ACTION_VIEW);
String typedata = "image/*";
lance.setType(typedata);
String phuri = "content://" + URI_AUTORITE
+ "/" + URI_CONTENU_FICHIERS
+ directory + filename;
Uri uri = Uri.parse(phuri);
lance.setDataAndType(uri, "image/*");
startActivity(lance);
But I am trying to go one step further to implement the display of a directory containing images. I tried to use the ClipData object to display several images, through this code :
Intent lance = new Intent();
lance.setAction(Intent.ACTION_VIEW);
String typedata = "image/*";
lance.setType(typedata);
String phuri = "content://" + URI_AUTORITE
+ "/" + URI_CONTENU_FICHIERS
+ directory + filename;
Uri uri = Uri.parse(phuri);
ClipData ensemble = ClipData.newRawUri("Photos", uri);
lance.setClipData(ensemble);
startActivity(lance);
It doesn't work : the Gallery app is launched and display the list of albums and doesn't call my File ContentProvider.
Dis I miss something or is it a problem for the Gallery app developpers ?
You should override getType() method of your content provider to return mime type of image like so
#Override
public String getType(Uri uri) {
return "image/*";
}

Categories

Resources