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);
}
Related
I have webview which we have php application loaded. the application lists item which the user selects. when a list is selected. it does a redirect with a file path from the server which is captured using the below code.
1.get the file name and extension from the url and use it too create a new file which we will use it for writing outputstream to it.
2. call the downloadFile() method to read the file
3. call the ShoWeDrawings() passing the filename to use it to read the file and pass it to open it using intent action_view with another app.
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// This is my web site, so do not override; let my WebView load the page
if(url.contains("Files") ) {
String filename = url.substring(url.lastIndexOf('/') +1);
String extStorageDirectory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/EASM";
File folder = new File(extStorageDirectory);
if (!folder.exists()) {
folder.mkdir();
}
File file = new File(folder, filename);
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile( url,file);
ShoWeDrawings(filename);
return true;
}
return false;
}
download class
public class Downloader {
private static Context context;
// public Context context ;
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(false);
c.setConnectTimeout(10000);
c.setReadTimeout(10000);
c.connect();
int status = c.getResponseCode();
// InputStream in = c.getErrorStream();
InputStream in = c.getInputStream();
// c.getErrorStream();
byte[] buffer = new byte[4096];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
in.close();
// Toast.makeText(context.getApplicationContext(), "A new file is downloaded successfully", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
ShoWeDrawings method
private void ShoWeDrawings(String filename) {
File file = new File( getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"/EASM/"+filename);
// Uri uri = Uri.fromFile(file);
try {
Intent mIntent = new Intent(Intent.ACTION_VIEW);
// mIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.fromFile(file));
// mIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file));
mIntent.setDataAndType(Uri.fromFile(file), "application/octet-stream");
mIntent.setPackage("com.solidworks.eDrawingsAndroid");
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent.createChooser(mIntent, "Choose Application");
startActivity(mIntent);
}
catch (Exception e)
{
e.printStackTrace();
}
}
now the problem comes with the opening of the file using the targeted app. i get a toast error message. Im not sure if its due to permissions or its the app that has problems. By the way i have upgraded to android 11 and i cant even view data/ folder on the tablet. i can only see the files via pc. The error message that im getting is - filename:error copying file to documents folder see picture below.
I tried to change the code and restarting the tablet thinking it might have been the updates that i pushed.
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.
I want to download a text file from a web url and save it locally on the device and use it in my app.
Code:
try {
File file = new File(getFilesDir(), "file.txt");
if (file.length() > 0) {
//File already exists and it is not empty
return;
}
URL url = new URL("https://www.abc.com/file.txt");
FileOutputStream fos = new FileOutputStream(file);
InputStream in = url.openStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.flush();
fos.close();
} catch (Exception e) {
// TODO:
}
As you can see, the code goes with getFilesDir() assuming that always exists. However there are few questions, with proper network connection and permissions:
Does my assumption of getFilesDir() fail in any case?
Are there any cases of either file not downloaded/wrong content etc.., with this code?
Once I faced an issue where the file is downloaded but has all encoded characters, no matter how may times I downloaded it, it still had the same encoded text. Only when I re-installer my app, then the proper text was downloaded. And never got that issue ever since. Any reason for that weird behavior?
EDIT:
Here is what I get as the content when I try to read the file which I downloaded(happens sometimes, 1 in 10) shown in the logcat:
Code to read the file:
BufferedReader inputReader= = new BufferedReader(
new InputStreamReader(new FileInputStream(file)));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
Log.e("inputString: ", inputString);
}
inputReader.close();
Thank You
Does my assumption of getFilesDir() fail in any case?
According to the documentation it should always work with no permissions required.
Are there any cases of either file not downloaded/wrong content etc..,
with this code?
Sure, I mean just a simple connection drop will cause download failure and so many other things can go wrong like missing required permission (android.permission.INTERNET), wrong encoding, disk full, ...
Once I faced an issue where the file is downloaded but has all encoded
characters, no matter how may times I downloaded it, it still had the
same encoded text. Only when I re-installer my app, then the proper
text was downloaded. And never got that issue ever since. Any reason
for that weird behavior?
It might have been an encoding issue, wrap your FileOutputStream in an OutputStreamWriter, which allows you to pass encoding parameter in the constructor.
Writer writer = new OutputStreamWriter(fos);
.
.
.
writer.write(buffer, 0, length);
The following example may be helpful:
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
That's not really an answer but an advice, use ion a networking library for Android.
From examples:
Ion.with(context)
.load("http://example.com/really-big-file.zip")
// have a ProgressBar get updated automatically with the percent
.progressBar(progressBar)
// and a ProgressDialog
.progressDialog(progressDialog)
// can also use a custom callback
.progress(new ProgressCallback() {#Override
public void onProgress(int downloaded, int total) {
System.out.println("" + downloaded + " / " + total);
}
})
.write(new File("/sdcard/really-big-file.zip"))
.setCallback(new FutureCallback<File>() {
#Override
public void onCompleted(Exception e, File file) {
// download done...
// do stuff with the File or error
}
});
All operations are done not in the UI thread, so the user always see a responsive app.
Try with below code:
public void downloadFile(){
String DownloadUrl = "Paste Url to download a text file hereā¦";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
request.setDescription("sample text file for testing"); //appears the same in Notification bar while downloading
request.setTitle("Sample.txt");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalFilesDir(getApplicationContext(),null, "sample.pdf");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
public static boolean isDownloadManagerAvailable(Context context) {
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return false;
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.providers.downloads.ui","com.android.providers.downloads.ui.DownloadList");
List <resolveinfo> list = context.getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
} catch (Exception e) {
return false;
}
}
I cannot really comment on what goes wrong in your case, I will post a snippet of a code I'm using to detect what type of file I'm targeting and then get it. This has always worked as expected for me. I've modified my "onPostExecute" method to suit my answer here and I've tried to keep the names of my variables similar to yours. I've omitted the download progress indication bar to simplify the snippet. The download has to be done in the background, therefore "AsyncTask" is used. For the snippet I use random text file from google.
final String file_url = "https://www.kernel.org/doc/Documentation/power/drivers-testing.txt";
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(file_url);
final String fileName = URLUtil.guessFileName(file_url, null, fileExtension);
final String path = Environment.getExternalStorageDirectory().toString() + "/" + fileName;
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(file_url);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream in = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(path);
byte buffer[] = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
in.close();
} catch (IOException e) {
Log.e("Downloading file", "Download Error", e);
}
return null;
}
#Override
public void onPostExecute(Void result) {
try {
File file = new File(path);
BufferedReader inputReader = new BufferedReader(new FileReader(file));
String inputString;
while ((inputString = inputReader.readLine()) != null) {
Log.e("inputString: ", inputString);
}
inputReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.execute();
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);
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.