Как остановить выполнение кода?
Ситуация следующая - есть программа для просмотра PDF по ссылке и она работает
но есть один нюанс когда я выхожу из activity (Выхожу из activity через onBackPressed() ) в момент загрузки , то получается что программа все равно грузит документ. Хотя уже не надо .
public class MainActivity2 extends AppCompatActivity implements DownloadFile.Listener {
LinearLayout root;
RemotePDFViewPager remotePDFViewPager;
Button btnDownload;
PDFPagerAdapter adapter;
ProgressBar progressBar;
private Vibrator Vibro;
public String loadUrl ="Тут будет ссылка";
@Override
public void onBackPressed() {
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
Toast.makeText(getApplicationContext(), R.string.page_loading, Toast.LENGTH_SHORT ).show();
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
root = (LinearLayout) findViewById(R.id.remote_pdf_root);
btnDownload = (Button) findViewById(R.id.btn_download);
onClick(null);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (adapter != null) {
adapter.close();
}
}
public void showDownloadButton() {
btnDownload.setVisibility(View.VISIBLE);
}
public void updateLayout() {
root.removeAllViewsInLayout();
root.addView(progressBar,
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
progressBar.setVisibility(View.GONE);
root.addView(btnDownload,
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
root.addView(remotePDFViewPager,
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Vibro = (Vibrator)this.getSystemService(VIBRATOR_SERVICE);
Vibro.vibrate(50);
Toast.makeText(getApplicationContext(), "мы тут ", Toast.LENGTH_SHORT ).show();
}
@Override
public void onSuccess(String url, String destinationPath) {
adapter = new PDFPagerAdapter(this, FileUtil.extractFileNameFromURL(url));
remotePDFViewPager.setAdapter(adapter);
updateLayout();
showDownloadButton();
}
@Override
public void onFailure(Exception e) {
e.printStackTrace();
showDownloadButton();
}
@Override
public void onProgressUpdate(int progress, int total) {}
public void onClick(View view) {
final Context ctx = this;
final DownloadFile.Listener listener = this;
remotePDFViewPager = new RemotePDFViewPager(ctx, loadUrl, listener);
remotePDFViewPager.setId(R.id.pdfViewPager);
}
}
/////
исходники RemotePDFViewPager
/*
* Copyright (C) 2016 Olmo Gallegos Hernández.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.pdfviewpager.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.viewpager.widget.ViewPager;
import java.io.File;
import es.voghdev.pdfviewpager.library.remote.DownloadFile;
import es.voghdev.pdfviewpager.library.remote.DownloadFileUrlConnectionImpl;
import es.voghdev.pdfviewpager.library.util.FileUtil;
public class RemotePDFViewPager extends ViewPager implements DownloadFile.Listener {
protected Context context;
protected DownloadFile downloadFile;
protected DownloadFile.Listener listener;
public RemotePDFViewPager(Context context, String pdfUrl, DownloadFile.Listener listener) {
super(context);
this.context = context;
this.listener = listener;
init(new DownloadFileUrlConnectionImpl(context, new Handler(), this), pdfUrl);
}
public RemotePDFViewPager(Context context,
DownloadFile downloadFile,
String pdfUrl,
DownloadFile.Listener listener) {
super(context);
this.context = context;
this.listener = listener;
init(downloadFile, pdfUrl);
}
public RemotePDFViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init(attrs);
}
private void init(DownloadFile downloadFile, String pdfUrl) {
setDownloader(downloadFile);
downloadFile.download(pdfUrl,
new File(context.getCacheDir(), FileUtil.extractFileNameFromURL(pdfUrl)).getAbsolutePath());
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a;
a = context.obtainStyledAttributes(attrs, R.styleable.PDFViewPager);
String pdfUrl = a.getString(R.styleable.PDFViewPager_pdfUrl);
if (pdfUrl != null && pdfUrl.length() > 0) {
init(new DownloadFileUrlConnectionImpl(context, new Handler(), this), pdfUrl);
}
a.recycle();
}
}
public void setDownloader(DownloadFile downloadFile) {
this.downloadFile = downloadFile;
}
@Override
public void onSuccess(String url, String destinationPath) {
listener.onSuccess(url, destinationPath);
}
@Override
public void onFailure(Exception e) {
listener.onFailure(e);
}
@Override
public void onProgressUpdate(int progress, int total) {
listener.onProgressUpdate(progress, total);
}
/**
* PDFViewPager uses PhotoView, so this bugfix should be added
* Issue explained in https://github.com/chrisbanes/PhotoView
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
try {
return super.onInterceptTouchEvent(ev);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
}
}
public class NullListener implements DownloadFile.Listener {
public void onSuccess(String url, String destinationPath) {
/* Empty */
}
public void onFailure(Exception e) {
/* Empty */
}
public void onProgressUpdate(int progress, int total) {
/* Empty */
}
}
}
////
DownloadFileUrlConnectionImpl
/*
* Copyright (C) 2016 Olmo Gallegos Hernández.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.pdfviewpager.library.remote;
import android.content.Context;
import android.os.Handler;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class DownloadFileUrlConnectionImpl implements DownloadFile {
private static final int KILOBYTE = 1024;
private static final int BUFFER_LEN = 1 * KILOBYTE;
private static final int NOTIFY_PERIOD = 150 * KILOBYTE;
Context context;
Handler uiThread;
Listener listener = new NullListener();
public DownloadFileUrlConnectionImpl(Context context, Handler uiThread, Listener listener) {
this.context = context;
this.uiThread = uiThread;
this.listener = listener;
}
@Override
public void download(final String url, final String destinationPath) {
new Thread(new Runnable() {
@Override
public void run() {
try {
File file = new File(destinationPath);
FileOutputStream fileOutput = new FileOutputStream(file);
HttpURLConnection urlConnection = null;
URL urlObj = new URL(url);
urlConnection = (HttpURLConnection) urlObj.openConnection();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
int counter = 0;
byte[] buffer = new byte[BUFFER_LEN];
int bufferLength = 0;
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
while ((bufferLength = in.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
counter += bufferLength;
if (listener != null && counter > NOTIFY_PERIOD) {
notifyProgressOnUiThread(downloadedSize, totalSize);
counter = 0;
}
}
urlConnection.disconnect();
fileOutput.close();
notifySuccessOnUiThread(url, destinationPath);
} catch (MalformedURLException e) {
notifyFailureOnUiThread(e);
} catch (IOException e) {
notifyFailureOnUiThread(e);
}
}
}).start();
}
protected void notifySuccessOnUiThread(final String url, final String destinationPath) {
if (uiThread == null) {
return;
}
uiThread.post(new Runnable() {
@Override
public void run() {
listener.onSuccess(url, destinationPath);
}
});
}
protected void notifyFailureOnUiThread(final Exception e) {
if (uiThread == null) {
return;
}
uiThread.post(new Runnable() {
@Override
public void run() {
listener.onFailure(e);
}
});
}
private void notifyProgressOnUiThread(final int downloadedSize, final int totalSize) {
if (uiThread == null) {
return;
}
uiThread.post(new Runnable() {
@Override
public void run() {
listener.onProgressUpdate(downloadedSize, totalSize);
}
});
}
protected class NullListener implements Listener {
public void onSuccess(String url, String destinationPath) {
/* Empty */
}
public void onFailure(Exception e) {
/* Empty */
}
public void onProgressUpdate(int progress, int total) {
/* Empty */
}
}
}
////
DownloadFile
/*
* Copyright (C) 2016 Olmo Gallegos Hernández.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.pdfviewpager.library.remote;
public interface DownloadFile {
void download(String url, String destinationPath);
interface Listener {
void onSuccess(String url, String destinationPath);
void onFailure(Exception e);
void onProgressUpdate(int progress, int total);
}
}