2017-02-06 3 views
0

У меня есть веб-просмотр, содержащий гиперссылки pdf (некоторые из них большие), когда пользователь нажимает на гиперссылку, которую начинает загружать pdf, а затем просматривается в pdf vieweR.Остановить загрузку при нажатии кнопки

Я хочу добавить кнопку отмены, которая останавливает текущую загрузку, как это возможно? Как я могу остановить постоянную загрузку

+0

Как вы обработки загрузки файлов? Вы переопределили 'shouldOverrideUrlLoading'' WebViewClient'? Вы использовали системный сервис 'DownloadManager'? – j2ko

+0

overrideurlloiading клиента webview –

ответ

0

Лучший и простой способ управления загрузками - использовать DownloadManager. Также WebView предоставляет API для установки прослушивателя загрузки, что значительно упрощает обработку загрузок - DownloadListener. Вот быстрый пример запуска и отмены загрузки, нажав на кнопку:

public class MainActivity extends AppCompatActivity { 
    private Long mOnGoingDownload; 
    private Button mCancel; 
    private WebView mWebView; 
    private DownloadManager mDownloadManger; 

    protected void cancelDownload() { 
     if (mOnGoingDownload != null) { 
      mDownloadManger.remove(mOnGoingDownload); 
      clearDownloadingState(); 
      Toast.makeText(this, "Download canceled", Toast.LENGTH_SHORT).show(); 
     } 
    } 

    protected void clearDownloadingState() { 
     unregisterReceiver(mDownloadCompleteListener); 
     mCancel.setVisibility(View.GONE); 
     mOnGoingDownload = null; 
    } 

    BroadcastReceiver mDownloadCompleteListener = new BroadcastReceiver() { 
     public void onReceive(Context ctx, Intent intent) { 
      clearDownloadingState(); 
      long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); 
      Uri fileUri = mDownloadManger.getUriForDownloadedFile(id); 
      //Open file in viewer 
      //... 
      Toast.makeText(ctx, fileUri.getLastPathSegment() + " downloaded", Toast.LENGTH_SHORT).show(); 
     } 
    }; 

    protected void startDownload(String url, String userAgent, String mimetype) { 
     Uri fileUri = Uri.parse(url); 
     String fileName = fileUri.getLastPathSegment(); 
     String cookies = CookieManager.getInstance().getCookie(url); 

     DownloadManager.Request request = new DownloadManager.Request(fileUri); 
     request.setMimeType(mimetype) 
       .addRequestHeader("cookie", cookies) 
       .addRequestHeader("User-Agent", userAgent) 
       .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); 
     //register receiver for download complete event 
     registerReceiver(mDownloadCompleteListener, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
     mCancel.setVisibility(View.VISIBLE); 
     mOnGoingDownload = mDownloadManger.enqueue(request); 
     Log.e("DownloadExample", "68|MainActivity::startDownload: Download of " + fileName + " started"); 
    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     mDownloadManger = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 

     mCancel = (Button)findViewById(R.id.cancelDownload); 
     mCancel.setVisibility(View.GONE); 
     mCancel.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       cancelDownload(); 
      } 
     }); 

     mWebView = (WebView) findViewById(R.id.webview); 
     mWebView.setWebViewClient(new WebViewClient(){ 
      @Override 
      public boolean shouldOverrideUrlLoading(WebView view, String url) { 
       view.loadUrl(url); 
       return true; 
      } 
     }); 
     mWebView.setDownloadListener(new DownloadListener() { 
      @Override 
      public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { 
       startDownload(url, userAgent, mimetype); 
      } 
     }); 

     mWebView.getSettings().setJavaScriptEnabled(true); 
     mWebView.loadUrl("http://www.engineerhammad.com/2015/04/Download-Test-Files.html"); 
    } 
} 

И основной макет:

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.example.andrii.webview.MainActivity"> 
    <WebView 
     android:id="@+id/webview" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight="1"> 
    </WebView> 
    <Button 
     android:layout_gravity="bottom" 
     android:id="@+id/cancelDownload" 
     android:layout_width="match_parent" 
     android:text="Cancel donload" 
     android:layout_height="wrap_content" /> 
</FrameLayout>