Java 无法在android应用程序中下载完整文件
下面是我的代码 来自活动类Java 无法在android应用程序中下载完整文件,java,android,Java,Android,下面是我的代码 来自活动类 Intent intent = new Intent(this, DownloadService.class); // Create a new Messenger for the communication back Messenger messenger = new Messenger(handler); intent.putExtra("MESSENGER", messenger); intent.
Intent intent = new Intent(this, DownloadService.class);
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
intent.setData(Uri.parse("http://www.abc.ezy.asia/E-MobApps/op.apk"));
intent.putExtra("urlpath", "http://www.abc.ezy.asia/E-MobApps/op.apk");
startService(intent);
我已重写了处理事件的服务类方法
// DownloadService Class
@Override
protected void onHandleIntent(Intent intent) {
Uri data = intent.getData();
String urlPath = intent.getStringExtra("urlpath");
String fileName = data.getLastPathSegment();
File output = new File(Environment.getExternalStorageDirectory(),fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
fos = new FileOutputStream(output.getPath());
byte dataB[] = new byte[1024];
InputStreamReader reader = new InputStreamReader(stream);
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
fos.flush();
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = output.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
}
}
在上面的代码中,我使用文件流和输入流读取器进行下载
当我尝试下载html文件时,完整的文件被下载到我的SD卡上。但当我尝试APK时。下载的文件有2.2 mb而不是2.4 mb的解析问题。请帮助我解决此问题。请尝试以下代码:
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(output.getPath());
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
input.close();
result = Activity.RESULT_OK;
我认为您的代码不会根据文件类型进行区分。请确保您知道APK的确切大小(可能是2.2),否则文件可能已损坏。为什么不在网上试试其他apk文件呢?谢谢。但是,当我通过浏览器下载文件时,它会完全下载。那么,当您尝试打开(安装)从应用程序下载的文件时,会发生什么情况?它是否表明它不完整或已损坏?