kriskbx / whatsapp-sharing

whatsapp sharing button + generator
http://kriskbx.github.io/whatsapp-sharing
MIT License
276 stars 80 forks source link

Sharing button don't work on webview of android #39

Open Giacomo92 opened 9 years ago

Giacomo92 commented 9 years ago

Hi, i se your code to add a share button on my website. It's works perfect from mobile browser, but when i try to click it from the webview of my app it gives me this screenshot- 15-apr-2015-20-52-43 I've just read this: https://github.com/kriskbx/whatsapp-sharing/issues/15

and I don't understand why does not work properly even if the webapp run over the native android browser.

kriskbx commented 9 years ago

You could try to combine this answer and the Android intent code from WhatsApp itself - of course you should replace url.startsWith("http://") with something that looks for the url scheme: whatsapp://...

kriskbx commented 9 years ago

Have you managed to get this working? It would be nice to share your solution here if others stumble upon the same problem.

Giacomo92 commented 9 years ago

No, i've been busy lately. As soon as possible I'll work on it and i share with you.

ghost commented 8 years ago

Thanks guys its works perfectly

      if(url != null && url.startsWith("whatsapp://"))
        {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));
            return true;

        }else
        {
            return false;
        }
gurmeetsinghmalhotra commented 8 years ago

I am unable to make it work. Where do I need to put this code? Can you please help me and also let me know the code for the share button which you are using.

ghost commented 8 years ago

Use this

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

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        if(url != null && url.startsWith("whatsapp://"))
        {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));
            return true;

        }else
        {
            return false;
        }

    }
nicks258 commented 7 years ago

Thanks @nishanthrk it works great.

anugrahahza commented 7 years ago

What if i have this code and how to integrate with your code ??

 @Override
 public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

 return super.shouldOverrideUrlLoading(view, request);

 }
imgauravanimator commented 5 years ago

I am new can you please help ,This is my Code dont know where is my mistake

package com.agraleaks.imgauravanimator;

import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.view.View; import android.graphics.Bitmap; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;

import com.agraleaks.imgauravanimator.Common.Config;

public class MainActivity extends AppCompatActivity implements OnRefreshListener {

private WebView webView;
private ProgressDialog dialog;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private SwipeRefreshLayout swipeLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeLayout.setOnRefreshListener(this);
    swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
            android.R.color.holo_green_light,
            android.R.color.holo_orange_light,
            android.R.color.holo_red_light);

    //WebView
    webView = (WebView)findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean  shouldOverrideUrlLoading(WebView view, String url) {
            if(url != null && url.startsWith("whatsapp://"))
            {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));
                return true;

            }else
            {
                return false;
            }
        }
    });
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            //hide loading image
            findViewById(R.id.imageView1).setVisibility(View.GONE);
            findViewById(R.id.progressBar1).setVisibility(View.GONE);
            //show webview
            findViewById(R.id.webView).setVisibility(View.VISIBLE);
        }

    });

    webView.loadUrl("http://www.agraleaks.com/");
    webView.setHorizontalScrollBarEnabled(false);
    webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setBackgroundColor(128);

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Config.STR_PUSH))
            {
                String message = intent.getStringExtra(Config.STR_PUSH);
                showNotification ("Agra Leaks- Fastest News Channel in the City",message);
            }
        }
    };

    onNewIntent(getIntent());

}

private void showNotification(String title, String message) {

    Intent intent = new Intent(getBaseContext(),MainActivity.class);
    intent.putExtra(Config.STR_KEY,message);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
    builder.setAutoCancel(true)
            .setWhen(System.currentTimeMillis())
            .setDefaults(Notification.DEFAULT_ALL)
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle(title)
            .setContentText(message)
            .setContentIntent(contentIntent);
    NotificationManager notificationManager = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1,builder.build());
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction()== KeyEvent.ACTION_DOWN){

        switch (keyCode){

            case KeyEvent.KEYCODE_BACK:
                if (webView.canGoBack()){

                    webView.goBack();
                }
                else {

                    finish();
                }
                return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

@Override
protected void onPause() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,new IntentFilter("registrationComplete"));
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,new IntentFilter(Config.STR_PUSH));
}

@Override
public void onRefresh() {
    new Handler().postDelayed(new Runnable() {
        @Override public void run() {
           // webView.reload();
           swipeLayout.setRefreshing(false);
            webView.loadUrl( "javascript:window.location.reload( true )" );

        }
    }, 5000);
}

}

arun2445 commented 5 years ago

Yes I have the same problem. this code is not working for us. Please help

webView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub

            if(url != null && url.startsWith("whatsapp://"))
            {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));
                return true;

            }else
            {
                return false;
            }

        }

    });
imgauravanimator commented 5 years ago

Arun try this way ; @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if(url != null && url.startsWith("whatsapp://"))
            {
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Your Text");
                sendIntent.setType("text/plain");
                sendIntent.setPackage("com.whatsapp");
                startActivity(sendIntent);
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));
                return true;

            }else
            {
                return false;
            }
        }

Hope this will work for you.

arun2445 commented 5 years ago

The Code you given is not working it shows same error again . net::ERR_UNKNOWN_URL_SCHEME. PLease help

I paste all the code below here please check and tell me if their is any mistake. Please help

package com.womenspassion.arun.womenspassionfashion;

import android.app.Activity; import android.app.AlertDialog; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar;

import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd;

import hotchemi.android.rate.AppRate;

public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener { WebView webView; ProgressBar progressBar; private SwipeRefreshLayout sr; InterstitialAd mInterstitialAd; private InterstitialAd interstitial; int count=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //rating Dialog box

    AppRate.with(this)
            .setInstallDays(1)
            .setLaunchTimes(3)
            .setRemindInterval(2)
            .monitor();

    AppRate.showRateDialogIfMeetsConditions(this);
    AppRate.with(this).clearAgreeShowDialog();

    //call dialog box

    if (!isConnected(MainActivity.this)) buildDialog(MainActivity.this).show();
    else {

    }

    //swipe refresh
    sr = (SwipeRefreshLayout) findViewById(R.id.sr);
    sr.setOnRefreshListener(this);

    //notificationtab
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationManager mnotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel mchannel = new NotificationChannel(Constants.CHANNEL_ID, Constants.CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
        mchannel.setDescription(Constants.CHANNEL_DESCRIPTION);
        mchannel.enableLights(true);
        mchannel.setLightColor(Color.RED);
        mchannel.enableVibration(true);
        mchannel.setVibrationPattern(new long[]{100, 200, 300, 400, 300, 200, 100});

        mnotificationManager.createNotificationChannel(mchannel);

    }

    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

// Prepare the Interstitial Ad interstitial = new InterstitialAd(MainActivity.this); // Insert the Ad Unit ID interstitial.setAdUnitId(getString(R.string.admob_ad)); interstitial.loadAd(adRequest); // Prepare an Interstitial Ad Listener interstitial.setAdListener(new AdListener() { public void onAdLoaded() { // Call displayInterstitial() function

        }

        @Override
        public void onAdClosed() {
            AdRequest adRequest1 = new AdRequest.Builder().build();
            interstitial.loadAd(adRequest1);
        }

        @Override
        public void onAdFailedToLoad(int i) {
            super.onAdFailedToLoad(i);

        }
    });

    webView = (WebView) findViewById(R.id.wbview);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    //progressbar
    progressBar = (ProgressBar) findViewById(R.id.prg);

    //improve webview performance
    webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    webView.getSettings().setAppCacheEnabled(true);
    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webSettings.setDomStorageEnabled(true);
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    webSettings.setUseWideViewPort(true);
    webSettings.setSavePassword(true);
    webSettings.setSaveFormData(true);
    webSettings.setEnableSmoothTransition(true);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if(url != null && url.startsWith("whatsapp://"))
            {
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Your Text");
                sendIntent.setType("text/plain");
                sendIntent.setPackage("com.whatsapp");
                startActivity(sendIntent);
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));
                return true;

            }else
            {
                return false;
            }
        }});

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressBar.setVisibility(View.VISIBLE);
            setTitle("Loading..");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
            setTitle(view.getTitle());
        }

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

        }

    });
    webView.loadUrl("https://womenspassionfashion.wooplr.com/");

};

@Override
public void onRefresh() {
    webView.reload();
    sr.setRefreshing(false);

}

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        //exit dialog box

        final AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
        builder.setMessage("Are you sure you want to do this?");
        builder.setCancelable(true);
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        AlertDialog alertDialog=builder.create();
        alertDialog.show();
    }

}

public void displayInterstitial() {

// If Ads are loaded, show Interstitial else show nothing. if (interstitial.isLoaded()) { interstitial.show(); } }

public boolean isConnected(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netinfo = cm.getActiveNetworkInfo();

    if (netinfo != null && netinfo.isConnectedOrConnecting()) {
        android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if((mobile != null &&  mobile.isConnectedOrConnecting()) || (wifi != null &&  wifi.isConnectedOrConnecting())) return true;
        else return false;
    } else
        return false;
}

public AlertDialog.Builder buildDialog(Context c) {

    AlertDialog.Builder builder = new AlertDialog.Builder(c);
    builder.setTitle("No Internet Connection");
    builder.setMessage("You need to have Mobile Data or wifi to access this. Press ok to Exit");

    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            finish();
        }
    });

    return builder;
}

}