am trying to download from web page some files by clinking the url with webview handling the download not the browser
if i use DownloadListener it works perfectly with one problem i cant see the progressbar
if i use the AsyncTask i have to put the url in the code to download it i can just click the url and start downloading
my question is how can i let the AsyncTask download any url from the web without sitting the
downloadFile.execute("the url to the file you want to download");
or how i can create progressbar for DownloadListener
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
new Thread(myThread).start();
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.setInitialScale(50);
webview.getSettings().setUseWideViewPort(true);
webview.setVerticalScrollBarEnabled(false);
webview.setHorizontalScrollBarEnabled(false);
webview.loadUrl("http://localhost/index.php");
webview.setWebViewClient(new DownloadWebViewClient());
webview.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
InputStream is;
try {
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
is = con.getInputStream();
// Path and File where to download the APK
String path = Environment.getExternalStorageDirectory() + "/apdroid/";
String fileName = url.substring(url.lastIndexOf('/') + 1);
File dir = new File(path);
dir.mkdirs(); // creates the download directory if not exist
File outputFile = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
// Save file from URL to download directory on external storage
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
String name = Environment.getExternalStorageDirectory() + "/apdroid/" + url.substring(url.lastIndexOf('/') + 1);
intent.setDataAndType(Uri.fromFile(new File(name)), "application/vnd.android.package-archive");
startActivity(intent);
}catch (IOException e) {
e.printStackTrace();
}
}
});
}
protected void install(String fileName) {
// TODO Auto-generated method stub
}
private Runnable myThread = new Runnable() {
#Override
public void run() {
while (myProgress < 100) {
try {
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
} catch (Throwable t) {
}
}
}
Handler myHandle = new Handler() {
#Override
public void handleMessage(Message msg) {
myProgress++;
myProgressBar.setProgress(myProgress);
}
};
};
private class HelloWebViewClient extends WebViewClient {
#Override
public void onReceivedError(WebView view,int errorCode,String description,String failingUrl) {
try {view.stopLoading();} catch(Exception e){}
try {view.clearView();} catch(Exception e){}
view.loadUrl("file:///android_asset/wifi.html");
}
}
i just want to have ProgressBar when i download any file from my page
and i cant use asyncTask because i have to put the files in the code not by clicking at them
You should probably be overriding the URL loading process, and recognize by some way if any URL is being loaded whose resource you would want to download.
As soon as you detect this, stop loading the page and start the AsyncTask with this URL.
Related
Need a help to solve my problem.
In my android webview a pdf which is generated using tcpdf is not working properly ...
It generates some garbage values in the pdf
//download file
myWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
myRequest.allowScanningByMediaScanner();
myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//new
myRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
//create download manager
DownloadManager myManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
myManager.enqueue(myRequest);
Toast.makeText(MainActivity.this, "Downloding file....", Toast.LENGTH_SHORT).show();
}
});
//TCPDF
myWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//start download
DownloadPDF downlooadPDF = new DownloadPDF();
downlooadPDF.execute(url, userAgent, contentDisposition);
//Toast.makeText(MainActivity.this, "Downloding ...", Toast.LENGTH_SHORT).show();
}
});
}
//TCPDF
private class DownloadPDF extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
File myDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).toString() + "/myPDF");
// create the directory if it does not exist
if (!myDir.exists()) myDir.mkdirs();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.connect();
//get filename from the contentDisposition
String filename = null;
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(sUrl[2]);
while (m.find()) {
filename = m.group(1);
}
File outputFile = new File(myDir, filename);
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
connection.disconnect();
output.flush();
output.close();
input.close();
displayPdf(); // a function to open the PDF file automatically
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void displayPdf() {
try {
Object filename = fileList();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/myPDF/" + filename);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (Exception e) {
Log.i("TAG", e.getMessage());
}
}
}
I have wrote this code for download pdf from url and file url is this-
String fileURL= "http://www.vivekananda.net/PDFBooks/History_of_India.pdf";
Code this
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.getResponseCode();
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();
}
}
but this shows file not found exception with response code 405.I dont know why this happened.Please help..!!
This is my code where i had create file in sd card-
Code this
public void createPdfFile(){
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
file = new File(folder, "storrage_data.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}`
After this i am calling download method in thread like this from onResume(); beacuse from onCreate it will give error "Network On Main Thread".where i am wrong now i don't konw :(
Code this
public void downloadFile(){
new Thread(new Runnable() {
#Override
public void run() {
Downloader.DownloadFile(url, file);
showPdf();
}
}).start();
}
The possible reason is the folder in which you want to does not exist. First check if it exist. Create it if not. Then create fileoutputstream and write to it.
I suggest you use the DownloadManager. There are too many problems that can arise during download to handle all of them yourself. Just think of temporary loss of connectivity in the middle of download...
Below is some code I pulled out of my app and slightly modified to get rid of parts you don't need.
public void downloadAndOpenPdf(String url,final File file) {
if(!file.isFile()) {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url));
req.setDestinationUri(Uri.fromFile(file));
req.setTitle("Some title");
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
unregisterReceiver(this);
if (file.exists()) {
openPdfDocument(file);
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
dm.enqueue(req);
Toast.makeText(this, "Download started", Toast.LENGTH_SHORT).show();
}
else {
openPdfDocument(file);
}
}
public boolean openPdfDocument(File file) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(target);
return true;
} catch (ActivityNotFoundException e) {
Toast.makeText(this,"No PDF reader found",Toast.LENGTH_LONG).show();
return false;
}
}
Your code is correct. Now you need to download your pdf file to External storage or wherever you want to download and save it.
Delete this code and try again.
//c.setRequestMethod("GET");
//c.setDoOutput(true);
//c.getResponseCode();
//c.connect();
I think URL.openConnection() has description of connection already, so c.connect() isn't necessary.
Not long age, I can open pdf in my webview using below my code.
view.loadUrl("https://docs.google.com/gview?embedded=true&url=" + str);
But suddenly it's not work.
I don't know the reason.
How can I open pdf in my webview??
Create a downloader class
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();
}
}
}
In your activity after setContentView(R.layout.main);write these lines
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("URL", file);
showPdf();
Write this method
public void showPdf()
{
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);
}
add these permissions in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I think this question is repeated, I get the solution
1) Type:
webView.loadUrl("https://docs.google.com/gview?url="+pdfUrl.get(position).url);
2) Don't forget to set webview client
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(getActivity());
progressDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}
});
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);
I'm building a private enterprise Android application. My goal is to detect when there is update available and offer user to download it. If user choose to download update file is downloaded and android app install prompt is showed.
I successfully check for update, the problem is that apk file is not downloaded (empty file is created) therefore "There is a problem parsing the package." error is showed in android app install prompt.
Code:
public void downloadfileto(String fileurl, String filename) {
String myString;
try {
FileOutputStream f = new FileOutputStream(filename);
try {
URL url = new URL(fileurl);
URLConnection urlConn = url.openConnection();
InputStream is = urlConn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 8000);
int current = 0;
while ((current = bis.read()) != -1) {
f.write((byte) current);
}
} catch (Exception e) {
myString = e.getMessage();
}
f.flush();
f.close();
install(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void install(String fileName) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(fileName)),
"application/vnd.android.package-archive");
startActivity(install);
}
Function downloadfileto is called with:
downloadfileto("http://some-url/ind.apk", "data/data/my.package.name/app.apk");
Even if you download successfully, you will not be able to install the APK file, as the installer process will not be able to read the file. Plus, as Chris Stratton points out, your hard-coded path is sloppy (on Android 4.1 and older) and catastrophic (on Android 4.2 and higher).
In terms of the download logic, downloading a byte at a time is unlikely to perform well. Try something like this (for a File named output and a URL named url):
HttpURLConnection c=(HttpURLConnection)url.openConnection();
c.setRequestMethod("GET");
c.setReadTimeout(15000);
c.connect();
FileOutputStream fos=new FileOutputStream(output.getPath());
BufferedOutputStream out=new BufferedOutputStream(fos);
try {
InputStream in=c.getInputStream();
byte[] buffer=new byte[8192];
int len=0;
while ((len=in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
}
finally {
fos.getFD().sync();
out.close();
}
I would like to thank you all for helping here. I solved the problem by opening php script on server that counts downloads with web view, detecting download, path of download and starting activity to install application.
Name of file is always in form "ind-version.apk" (Example: ind-1-0.apk) and because I get version number of new update when I check for updates I decided to put it in extras and use it to determine file name.
Code:
WebView myWebView = (WebView) findViewById(R.id.helpview);
showDialog();
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl(url);
myWebView.getSettings().setJavaScriptEnabled(false);
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dismissDialog();
}
});
myWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
Bundle extras = getIntent().getExtras();
String v = extras.getString("v");
v = v.replace(".", "-");
Log.i("File", v);
File loc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.i("File", loc.toString() + "/ind-" + v + ".apk");
install(loc.toString() + "/ind-" + v + ".apk");
}
});
And install:
protected void install(String fileName) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(fileName)),
"application/vnd.android.package-archive");
startActivity(install);
}