问题
In my application i'm trying to download PDF file from server and storing it in SD card, but when i try to download, the download always failed and the logcat says no handler found. i need help to solve this problem, please help me. thank you
downloadText.java
package mobile.download;
import java.io.*;
import java.net.*;
import java.util.regex.Pattern;
import mobile.config.Kondownload;
import com.karismaelearning.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.TextView;
public class DownloadText extends Activity{
public Kondownload linkurl;
String url;
String SERVER_URL;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linkdownload);
TextView mTextLink = (TextView) findViewById(R.id.LinkDownload);
Bundle bundle = this.getIntent().getExtras();
String param1 = bundle.getString("keyIdc");
String param2 = bundle.getString("keyReference");
linkurl = new Kondownload(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/moodledata/"+param1+"/"+param2;
URLConnection urlConnection = null;
try{
URL url = new URL(SERVER_URL);
//Opening connection of currrent url
urlConnection = url.openConnection();
urlConnection.connect();
//int lenghtOfFile = urlConnection.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/pdf/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, param2);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = url.openStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("--pdf downloaded--ok--"+SERVER_URL);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
mTextLink.setText(SERVER_URL);
Pattern pattern = Pattern.compile(SERVER_URL);
Linkify.addLinks(mTextLink, pattern, "");
}
}
logcat
06-06 13:18:13.371: W/System.err(1056): java.io.FileNotFoundException: /mnt/sdcard/pdf/Dokumen/Dogmatika_1.pdf (No such file or directory)
06-06 13:18:13.371: W/System.err(1056): at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
06-06 13:18:13.391: W/System.err(1056): at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
06-06 13:18:13.391: W/System.err(1056): at java.io.FileOutputStream.<init>(FileOutputStream.java:94)
06-06 13:18:13.402: W/System.err(1056): at java.io.FileOutputStream.<init>(FileOutputStream.java:66)
06-06 13:18:13.402: W/System.err(1056): at mobile.download.DownloadText.onCreate(DownloadText.java:85)
06-06 13:18:13.402: W/System.err(1056): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-06 13:18:13.402: W/System.err(1056): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-06 13:18:13.402: W/System.err(1056): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-06 13:18:13.402: W/System.err(1056): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-06 13:18:13.402: W/System.err(1056): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-06 13:18:13.402: W/System.err(1056): at android.os.Handler.dispatchMessage(Handler.java:99)
06-06 13:18:13.402: W/System.err(1056): at android.os.Looper.loop(Looper.java:123)
06-06 13:18:13.402: W/System.err(1056): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-06 13:18:13.402: W/System.err(1056): at java.lang.reflect.Method.invokeNative(Native Method)
06-06 13:18:13.411: W/System.err(1056): at java.lang.reflect.Method.invoke(Method.java:507)
06-06 13:18:13.411: W/System.err(1056): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-06 13:18:13.411: W/System.err(1056): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-06 13:18:13.411: W/System.err(1056): at dalvik.system.NativeStart.main(Native Method)
06-06 13:18:13.861: I/ActivityManager(61): Displayed com.karismaelearning/mobile.download.DownloadText: +649ms
06-06 13:18:15.101: I/ActivityManager(61): Starting: Intent { act=android.intent.action.VIEW dat=http://10.0.2.2/moodledata/2/Dokumen/Dogmatika_1.pdf cmp=com.android.browser/.BrowserActivity (has extras) } from pid 1056
06-06 13:18:15.831: I/ActivityManager(61): Displayed com.android.browser/.BrowserActivity: +675ms
06-06 13:18:17.271: W/InputManagerService(61): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@40554818 (uid=10020 pid=378)
06-06 13:18:17.781: D/webviewglue(378): nativeDestroy view: 0x3e4820
06-06 13:18:18.541: I/DownloadManager(218): Initiating request for download 22
06-06 13:18:19.281: W/DownloadManager(218): Aborting request for download 22: no handler found for this download type
回答1:
check below code: its work in >= 9 Android API.
public void file_download(String uRl) {
//uRl = ;
File direct = new File(Environment.getExternalStorageDirectory()
+ "/dhaval_files");
if (!direct.exists()) {
direct.mkdirs();
}
DownloadManager mgr = (DownloadManager) this
.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir("/dhaval_files", "lecture3.pdf");
mgr.enqueue(request);
}
call above method using: file_download("http://moss.csc.ncsu.edu/~mueller/g1/lecture3.pdf");
For < 9 Android API use this way:
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockActivity;
public class MainActivity extends Activity {
ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setTheme(R.style.Theme_Sherlock_Light);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// execute this when the downloader must be fired
DownloadFile downloadFile = new DownloadFile();
downloadFile
.execute("http://moss.csc.ncsu.edu/~mueller/g1/lecture3.pdf");
}
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/lecture3.pdf");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
}
}
both code is working it download PDF file.
Here is Best Answer
回答2:
Try this out
var win = Ti.UI.createWindow({
navBarHidden: true,
backgroundColor: 'blue'
});
win.open();
var button = Ti.UI.createButton({
title: 'Get PDF',
height: 50,
width: 200,
top: 20
});
win.add(button);
button.addEventListener('click', function(e) {
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function() {
var f = Ti.Filesystem.getFile(Titanium.Filesystem.externalStorageDirectory,"test.pdf");
f.write(this.responseData);
var intent = Ti.Android.createIntent({
action : Ti.Android.ACTION_VIEW,
type : 'application/pdf',
data : f.getNativePath()
});
Ti.Android.currentActivity.startActivity(intent);
};
xhr.open("GET", "http://www.appcelerator.com/assets/The_iPad_App_Wave.pdf");
xhr.send();
});
Or try this out
public void downloadPdfContent(String urlToDownload){
URLConnection urlConnection = null;
try{
URL url = new URL(urlToDownload);
//Opening connection of currrent url
urlConnection = url.openConnection();
urlConnection.connect();
//int lenghtOfFile = urlConnection.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/1/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "test.pdf");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = url.openStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("--pdf downloaded--ok--"+urlToDownload);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
来源:https://stackoverflow.com/questions/16953355/got-error-when-try-to-download-pdf-file