I am trying to download the file from app server using the IntentService. It is working fine when i want to download the file completely. but I want to cancel the file downloading in the middle of downloading. but it fails. I have tried to stop the IntentService but Service is not stopping. after that i tried to close the InputStream provided by the HttpConnectionUrl. then it is generation an error. please help me to solve this issue. please don't make a duplicate question.
@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();
}
}
when i am trying to close the input stream, getting the following exception.
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)