Как вызвать onFailure в библиотеке pdfviewpager:library?
Мне нужно остановить загрузку Pdf когда я закрываю activity .
https://github.com/voghDev/PdfViewPager
Для остановки кода
////
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);
}
}
Ответы (1 шт):
Автор решения: ЮрийСПб
→ Ссылка
Встроенной в библиотеку возможности такой нет.
Однако есть возможность передать в конструктор RemotePDFViewPager свою реализацию интерфейса DownloadFile, в которой можно такую возможность реализовать.
Например можно сделать как-то так (дополненная, нетестированная и неидеальная копия DownloadFileUrlConnectionImpl):
import android.content.Context;
import android.os.Handler;
import android.util.Log;
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;
private Thread thread;
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) {
thread = new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection urlConnection = null;
InputStream in = null;
FileOutputStream fileOutput = null;
try {
File file = new File(destinationPath);
fileOutput = new FileOutputStream(file);
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;
in = new BufferedInputStream(urlConnection.getInputStream());
while ((bufferLength = in.read(buffer)) > 0) {
if (!thread.isInterrupted()) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
counter += bufferLength;
if (listener != null && counter > NOTIFY_PERIOD) {
notifyProgressOnUiThread(downloadedSize, totalSize);
counter = 0;
}
} else {
throw new InterruptedException();
}
}
notifySuccessOnUiThread(url, destinationPath);
} catch (MalformedURLException e) {
notifyFailureOnUiThread(e);
} catch (IOException e) {
notifyFailureOnUiThread(e);
} catch (InterruptedException e) {
Log.d(DownloadFileUrlConnectionImpl.class.getSimpleName(), "Thread interrupted!");
} finally {
try {
if (in != null) {
in.close();
}
if (urlConnection != null) {
urlConnection.disconnect();
}
if (fileOutput != null) {
fileOutput.close();
}
} catch (IOException ignored) {
}
}
}
});
thread.start();
}
public void stopDownload() {
thread.interrupt();
}
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 */
}
}
}
Добавьте этот файл себе в проект и используйте так:
DownloadFileUrlConnectionImpl d = DownloadFileUrlConnectionImpl(this, new Handler(), this)
remotePDFViewPager = new RemotePDFViewPager(ctx, d, loadUrl, listener);
Когда вам надо будет остановить загрузку - вызовите метод остановки так:
d.stopDownload();
Вызвать его можно, например в методе onStop() активити.