4

i am very new to Android but i create a webview and it displays a wordpress page with a Download Link for a PDF in it, but when i tap on it nothing happends, i hope you can help me :)

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.freizeitpark.plus"
    android:versionCode="1"
    android:versionName="1.2" >

    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
 <uses-permission android:name="android.permission.CALL_PHONE" />
    <application
        android:icon="@drawable/app_icon"
        android:label="@string/app_name" >
        <activity
            android:configChanges="keyboard|keyboardHidden|orientation"
            android:name="com.google.ads.AdActivity" >
        </activity>
        <activity
            android:label="@string/app_name"
            android:name=".SplashActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
             android:configChanges="touchscreen|keyboardHidden|orientation"
            android:launchMode="singleTop"
            android:name="DroidWebViewActivity" >
        </activity>

    </application>

</manifest>

Main Activity

package com.freizeitpark.plus;

import com.freizeitpark.plus.info.Info;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.PluginState;
import android.widget.ProgressBar;



public class DroidWebViewActivity extends Activity {
    /** Called when the activity is first created. */
    Context con;
    private WebView fweBview;
    private WebSettings webSettings;
    ProgressBar progressBar;

    String url = Info.WebUrl;
    String url22 = Info.WebUrl22;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        con = this;
        try {
            if (!SharedPreferencesHelper.isOnline(con)) {
                AlertMessage.showMessage(con, "", "No internet connection");
                return;
            }
            updateWebView(url);

        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    private class HelloWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

            progressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && fweBview.canGoBack()) {
            fweBview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    private void updateWebView(String url) {
        // TODO Auto-generated method stub
        progressBar = (ProgressBar) findViewById(R.id.progressBar12);
        fweBview = (WebView) findViewById(R.id.fbwebView);
        fweBview.getSettings().setJavaScriptEnabled(true);
        fweBview.getSettings().setDomStorageEnabled(true);
        fweBview.getSettings().setPluginState(PluginState.ON);
        webSettings = fweBview.getSettings();

        webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setBuiltInZoomControls(true);

        fweBview.getSettings().setPluginsEnabled(true);
        fweBview.loadUrl(url);

        fweBview.setWebViewClient(new HelloWebViewClient());

    }

    // /---- Rating Button-----------------------------

    public void btnRating(View v) {

        try {

            alertbox(null, null);

        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    protected void alertbox(String title, String mymessage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Dir gefällt die Freizeitparks Guide+ App? Dann würden wir uns über eine Bewertung sehr freuen :) ").setCancelable(
                false).setTitle("").setPositiveButton("Jetzt bewerten",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // finish the current activity
                        // AlertBoxAdvance.this.finish();
                        /*
                         * Intent myIntent = new Intent(
                         * Settings.ACTION_SECURITY_SETTINGS);
                         * startActivity(myIntent);
                         */
                        Intent viewIntent = new Intent(
                                "android.intent.action.VIEW",
                                Uri
                                        .parse(Info.GooglePlayAppUrl));
                        startActivity(viewIntent);
                        dialog.cancel();
                    }
                }).setNegativeButton("Später",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // cancel the dialog box

                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    // ------------ Share button---------------------

    public void btnShare(View v) {

        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                "    ");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Jetzt die Freizeitparks Guide+ App endlich im Play Store hier kannst du Sie dir kostenlos herunterladen https://play.google.com/store/apps/details?id=com.freizeitpark.plus");
        startActivity(Intent.createChooser(sharingIntent, "Weiterempfehlen"));
    }

    // ------------ Home button---------------------
    public void btnHome(View v) {
        try {
            updateWebView(url);
        } catch (Exception e) {
            // TODO: handle exception
        }

        // Intent i = new Intent(DroidWebViewActivity.this,
        // DroidWebViewActivity.class); // your class
        // startActivity(i);

    }

    // ------------ Email button---------------------
    public void btnEmail(View v) {

        Intent email = new Intent(Intent.ACTION_SEND);
        email.putExtra(Intent.EXTRA_EMAIL,
                new String[] { "" });
        email.putExtra(Intent.EXTRA_SUBJECT, Info.eMailSubject);
        email.putExtra(Intent.EXTRA_TEXT, Info.eMailDetails);
        email.setType("message/rfc822");
        startActivity(Intent.createChooser(email, "Per E-Mail :"));

    }

    // ------------ Call button---------------------
    public void btnPhone(View v) {
        try {
            updateWebView(url22);
        } catch (Exception e) {
            // TODO: handle exception
        }

        // Intent i = new Intent(DroidWebViewActivity.this,
        // DroidWebViewActivity.class); // your class
        // startActivity(i);

    }


    }

HOPE YOU CAN HELP ME SO MUCH! :)

2 Answers 2

6

Try to add this to to your code: (probably in your updateWebView method) This will intercept any downloads and send them to the standard android download manager.

 mWebView.setDownloadListener(new DownloadListener() {
    public void onDownloadStart(String url, String userAgent,
            String contentDisposition, String mimetype,
            long contentLength) {
                Request request = new Request( Uri.parse(url));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myPDFfile.pdf"); 
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);        
   }
});

Note that this will use the same filename everytime, so your file may get replaced unless you modify the code to use a different filename.

4
  • 1
    don't work i copy that to my main activity but i just get errors and the app crash x.x i am very new to android but i dont get it to work :( Commented Feb 16, 2015 at 14:10
  • I bet the reason is because setDestinationInExternalPublicDir is called and there's no WRITE_EXTERNAL_STORAGE permission requested: java.lang.SecurityException: need WRITE_EXTERNAL_STORAGE permission to use DESTINATION_FILE_URI: uid 10406 does not have android.permission.WRITE_EXTERNAL_STORAGE.
    – miq
    Commented Nov 25, 2015 at 8:42
  • From fragment, constant should be referenced as Context.DOWNLOAD_SERVICE
    – Gene Bo
    Commented Jun 13, 2016 at 17:16
  • "setDownloadListener sets the listener when the WebView doesn't think the content can be handled by the rendering engine", from/thanks to: stackoverflow.com/a/5798702/2162226
    – Gene Bo
    Commented Jun 13, 2016 at 18:21
0

JonasCz's answer updated for kotlin users, requesting storage permissions previously.

    webview.setDownloadListener { url, _, _, _, _ ->
        if (ContextCompat.checkSelfPermission(context!!, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity!!, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_CODE)
        } else {
            val request = DownloadManager.Request(Uri.parse(url))
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myPDFfile.pdf")
            val dm = context?.getSystemService(DOWNLOAD_SERVICE) as DownloadManager?
            dm!!.enqueue(request)
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.