我正在尝试使用IntentService从app服务器下载文件。当我想完全下载文件时它工作正常。但我想在下载过程中取消文件下载。但它失败了。我试图阻止IntentService,但服务没有停止。之后,我试图关闭HttpConnectionUrl提供的InputStream。然后是生成错误。请帮我解决这个问题。 请不要提出重复的问题。
@Override
protected void onHandleIntent(Intent intent) {
final String url = intent.getStringExtra(ConstantUtils.EXTRA_URL);
mOutputFileName = (File) intent.getSerializableExtra(ConstantUtils.EXTRA_FILE_NAME);
mHttpURLConnectionUtil = new HttpURLConnectionUtil();
mHttpURLConnectionUtil.setOnDownloadProgress(this);
try {
mHttpURLConnectionUtil.downloadFile(url, mOutputFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void downloadFile(String url, File outputFile) throws IOException {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
mInputStream = new DataInputStream(u.openStream());
mOutputStream = new DataOutputStream(new FileOutputStream(outputFile));
byte[] buffer = new byte[CONTENT_LENGTH];
int count;
int total = 0;
while ((count = mInputStream.read(buffer)) != -1) {
total += count;
mOutputStream.write(buffer, 0, count);
}
mOutputStream.write(buffer);
closeStream();
}
private void closeStream() throws IOException {
if (mInputStream != null) {
mInputStream.close();
}
if (mOutputStream != null) {
mOutputStream.flush();
mOutputStream.close();
}
}
当我尝试关闭输入流时,获得以下异常。
java.lang.NullPointerException: Attempt to read from field 'int com.android.okio.Segment.limit' on a null object reference
at com.android.okio.OkBuffer.write(OkBuffer.java:574)
at com.android.okio.OkBuffer.read(OkBuffer.java:610)
at com.android.okio.RealBufferedSource.read(RealBufferedSource.java:56)
at com.android.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:465)
at com.android.okhttp.internal.Util.skipAll(Util.java:227)
at com.android.okhttp.internal.http.HttpConnection.discard(HttpConnection.java:235)
at com.android.okhttp.internal.http.HttpConnection$FixedLengthSource.close(HttpConnection.java:487)
at com.android.okio.RealBufferedSource.close(RealBufferedSource.java:204)
at com.android.okio.RealBufferedSource$1.close(RealBufferedSource.java:187)
at java.io.FilterInputStream.close(FilterInputStream.java:64)
at com.meditation.minute.utils.HttpURLConnectionUtil.closeStream(HttpURLConnectionUtil.java:59)
at com.meditation.minute.utils.HttpURLConnectionUtil.cancelDownloading(HttpURLConnectionUtil.java:68)
at com.meditation.minute.service.DownloadAudioIntentService$1$1.run(DownloadAudioIntentService.java:38)