2016-02-20 14 views
12

Sto caricando una pagina Web in WebView. C'è un link nella pagina web, che sul desktop scaricherà il file, ma nell'app il link dovrebbe visualizzare un Toast che dice che il collegamento è disabilitato per l'app.Ottieni il valore href dal tag di ancoraggio in Android WebView quando si fa clic sul collegamento

Non sono sicuro di come ottenere il valore da href del tag di ancoraggio, quando si fa clic sul collegamento.

<a class="btn btn-primary" download="http://xx.xxx.com/wp-content/uploads/2015/11/abc-27-15.mp3" href="http://xx.xxx.com/wp-content/uploads/2015/11/abc-27-15.mp3"> 
<i class="fa fa-download"></i> Download Audio</a> 

Qualcuno può condividere un'idea o qualsiasi codice di esempio su come farlo.

EDIT: 1

Qui è quello che sto facendo attualmente:

private static final String URL = "http://xx.xxx.com/wp-content/uploads/"; 

webView.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 

       if (event.getAction() == MotionEvent.ACTION_DOWN) { 

        WebView.HitTestResult hr = ((WebView) v).getHitTestResult(); 
        String extra = hr.getExtra(); 

        if (extra != null && extra.startsWith(URL) && extra.endsWith(".mp3")) { 
         Log.d("WebviewActivity", "Extra: " + extra); 
         Log.d("WebviewActivity", "Contains URL"); 

         return true; 
        } 
       } 

       return false; 
      } 
     }); 

Il problema di questo approccio è: quando clicco sul link, ho ottenere l'URL in più. Funziona bene fino a qui. Ma, dalla prossima volta, non importa dove clicco sulla webview, lo stesso extra verrà restituito. Quindi, anche se clicco su un'immagine dopo aver cliccato sull'URL, ottengo lo stesso URL nell'extra. Non sono sicuro se faccio qualcosa di sbagliato. O è questo l'approccio corretto.

Per favore fatemi sapere se avete bisogno di ulteriori dettagli.

EDIT: 2

private Handler mHandler = new Handler() { 

     @Override 
     public void handleMessage(Message msg) { 
      // Get link-URL. 
      String url = (String) msg.getData().get("url"); 

      // Do something with it. 
      if (url != null) { 
       Log.d(TAG, "URL: "+url); 
      } 
     } 
    }; 



     webView.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 

       if (event.getAction() == MotionEvent.ACTION_DOWN) { 

        WebView.HitTestResult hr = ((WebView) v).getHitTestResult(); 


        if (hr.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) { 

         Message msg = mHandler.obtainMessage(); 
         webView.requestFocusNodeHref(msg); 
        } 


       } 

       return false; 
      } 
     }); 



     webView.loadUrl(mUrl); 

    } 

Ora, ho l'URL che viene cliccato in ultimo evento action_down. Come ottenere l'URL corrente?

EDIT 3 (Tentativo con webviewclient:

private class MyWebViewClient extends WebViewClient { 

     private static final String URL = "xx.xxx.com/wp-content/uploads/"; 

     @Override 
     public void onPageStarted(WebView view, String url, Bitmap favicon) { 
      super.onPageStarted(view, url, favicon); 

      if (!isFinishing()) 
       mProgressDialog.show(); 
     } 

     @Override 
     public void onPageFinished(WebView view, String url) { 
      super.onPageFinished(view, url); 
      mProgressDialog.dismiss(); 
     } 

     @Override 
     public void onReceivedError(WebView view, int errorCode, 
            String description, String failingUrl) { 
      super.onReceivedError(view, errorCode, description, failingUrl); 

      Toast.makeText(WebviewActivity.this, 
        "Please check your internet " + "connection and try again", 
        Toast.LENGTH_SHORT).show(); 
     } 


     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 

      Log.d("xxx", "Url: " + url); 

      if(url.contains(URL)) { 
       Log.d("xxx", "Url Contains: " + URL); 
       return true; 
      } 

      return false; 
     } 

    } 


mMyWebViewClient = new MyWebViewClient(); 
     webView.setWebViewClient(mMyWebViewClient); 

uscita nel logcat quando il link viene cliccato:.

03-01 15:38:19.402 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:553] focusedNodeChanged: isEditable [false] 
03-01 15:38:19.428 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:253] updateKeyboardVisibility: type [0->0], flags [0], show [true], 
03-01 15:38:19.428 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:326] hideKeyboard 
03-01 15:38:19.429 19626-19626/com.xx.xxx D/cr_Ime: [InputMethodManagerWrapper.java:56] isActive: true 
03-01 15:38:19.429 19626-19626/com.xx.xxx D/cr_Ime: [InputMethodManagerWrapper.java:65] hideSoftInputFromWindow 

risposta

1

La maggior parte del lavoro può essere fatto a lato pagina web stessa si hanno per scrivere il java script per identificare quale dispositivo sta accedendo alla pagina (mobile, desktop ecc.) se il suo cellulare usa la tecnica di collegamento script java per chiamare il codice nativo di Android per mostrare il messaggio di Toast.

http://developer.android.com/guide/webapps/webview.html

WebView webView = (WebView) findViewById(R.id.webview); 
webView.addJavascriptInterface(new WebAppInterface(this), "Android"); 

WebAppInterface.java

public class WebAppInterface { 
    Context mContext; 

    /** Instantiate the interface and set the context */ 
    WebAppInterface(Context c) { 
     mContext = c; 
    } 

    /** Show a toast from the web page */ 
    @JavascriptInterface 
    public void showToast(String toast) { 
     Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); 
    } 
} 

YourHTML Pagina (questo campione ha un pulsante di scatto)

<input type="button" value="Say hello" onClick="showAndroidToast('Hello 
      Android!')" /> 

    <script type="text/javascript"> 
    function showAndroidToast(toast) { 
     Android.showToast(toast); 
    } 
</script> 
4

Poiché si utilizza un WebView e il link non è Java script questo è molto facile da ottenere con un WebViewClient che puoi utilizzare per monitorare la tua WebView

myWebView.setWebViewClient(new WebViewClient() { 

    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     // check something unique to the urls you want to block 
     if (url.contains("xx.xxx.com")) { 
      Toast.make... //trigger the toast 
      return true; //with return true, the webview wont try rendering the url 
     } 
     return false; //let other links work normally 
    } 

}); 

È possibile che, poiché l'URL termina con .mp3, il file viene trattato come una risorsa. Si dovrebbe anche sovrascrivere il metodo shouldInterceptRequest di WebView Client per controllarlo.

@Override 
@TargetApi(Build.VERSION_CODES.LOLLIPOP) 
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { 
    String url = request.getUrl().toString(); 
    Log.d("XXX", "Url from API21 shouldInterceptRequest : " + url); 
    if (url.contains(URL)) { 
     return new WebResourceResponse("text/html", "UTF-8", "<html><body>No downloading from app</body></html>"); 
    } else { 
     return null; 
    } 
} 

public WebResourceResponse shouldInterceptRequest (WebView view, String url) { 
    Log.d("XXX", "Url from shouldInterceptRequest : " + url); 
    if (url.contains(URL)) { 
     return new WebResourceResponse("text/html", "UTF-8", "<html><body>No downloading from app</body></html>"); 
    } else { 
     return null; 
    } 
} 
+0

Siamo spiacenti per la risposta tardiva. Ho provato questo approccio all'inizio. Ma quando clicco sul link, shouldOverrideUrlLoading non viene chiamato.L'unica volta che ottengo l'url è quando uso onTouchListener sul WebView come menzionato nell'articolo del codice Question –

+0

Se il client webview è impostato correttamente sulla webview, ottenere gli URL causano sempre la chiamata del metodo. Se si tratta di un modulo post non è il caso, ma hai detto un link di ancoraggio. Hai usato questo allo stesso tempo dell'ascoltatore del tocco? Perché ovviamente non funzionerà quando si annulla l'evento –

+0

Ho aggiornato la domanda con WebViewClient. Per favore guarda. Non sto usando entrambi allo stesso tempo. Prima ho provato con WebViewClient, ma, non ho potuto ottenere l'url da shouldOverrideUrlLoading. Quindi, stavo provando con onTouchListener. –

Problemi correlati