wahtsapp

Created: March 20, 2026 at 7:27 am

Expires: Never

Syntax: Plain Text

package com.pingxo.app;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Base64;

import androidx.annotation.NonNull;

import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@CapacitorPlugin(name = "WhatsAppShare")
public class WhatsAppSharePlugin extends Plugin {

    @PluginMethod
    public void shareImage(PluginCall call) {
        String imageUrl = call.getString("imageUrl");
        if (imageUrl == null || imageUrl.isEmpty()) {
            imageUrl = call.getString("imgUrl");
        }
        final String normalizedImageUrl = imageUrl;
        String imageBase64 = call.getString("imageBase64");

        if ((normalizedImageUrl == null || normalizedImageUrl.isEmpty()) && (imageBase64 == null || imageBase64.isEmpty())) {
            call.reject("imageUrl or imageBase64 is required");
            return;
        }

        new Thread(() -> {
            try {
                Uri imageUri = null;
                if (imageBase64 != null && !imageBase64.isEmpty()) {
                    imageUri = cacheBase64Image(imageBase64);
                }
                if (imageUri == null && normalizedImageUrl != null && !normalizedImageUrl.isEmpty()) {
                    imageUri = downloadAndCacheImage(normalizedImageUrl);
                }
                if (imageUri == null) {
                    call.reject("Failed to prepare image for WhatsApp");
                    return;
                }

                String targetPackage = resolveWhatsAppPackage();
                if (targetPackage == null) {
                    call.reject("WhatsApp is not installed");
                    return;
                }

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_STREAM, imageUri);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setPackage(targetPackage);

                final Uri finalImageUri = imageUri;
                getActivity().runOnUiThread(() -> {
                    try {
                        getContext().grantUriPermission(targetPackage, finalImageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        getActivity().startActivity(intent);

                        JSObject result = new JSObject();
                        result.put("success", true);
                        call.resolve(result);
                    } catch (Exception e) {
                        String detail = e.getMessage();
                        if (detail == null || detail.isEmpty()) {
                            detail = e.getClass().getSimpleName();
                        }
                        call.reject("Error sharing to WhatsApp: " + detail, e);
                    }
                });
            } catch (Exception e) {
                String detail = e.getMessage();
                if (detail == null || detail.isEmpty()) {
                    detail = e.getClass().getSimpleName();
                }
                call.reject("Error sharing to WhatsApp: " + detail, e);
            }
        }).start();
    }

    private String resolveWhatsAppPackage() {
        PackageManager packageManager = getContext().getPackageManager();
        String[] packages = new String[] { "com.whatsapp", "com.whatsapp.w4b" };
        for (String pkg : packages) {
            try {
                packageManager.getPackageInfo(pkg, 0);
                return pkg;
            } catch (PackageManager.NameNotFoundException ignored) {
            }
        }
        return null;
    }

    private Uri cacheBase64Image(@NonNull String imageBase64) throws IOException {
        byte[] imageBytes = Base64.decode(imageBase64, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        if (bitmap == null) {
            return null;
        }
        return cacheBitmap(bitmap);
    }

    private Uri downloadAndCacheImage(@NonNull String imageUrl) throws IOException {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(imageUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            inputStream = new BufferedInputStream(connection.getInputStream());
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap == null) {
                return null;
            }
            return cacheBitmap(bitmap);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private Uri cacheBitmap(@NonNull Bitmap bitmap) throws IOException {
        String filename = "pingxo_whatsapp_" + System.currentTimeMillis() + ".png";
        ContentResolver resolver = getContext().getContentResolver();
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.Images.Media.IS_PENDING, 1);
        }

        Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        if (imageUri == null) {
            return null;
        }

        try (java.io.OutputStream out = resolver.openOutputStream(imageUri)) {
            if (out == null) {
                return null;
            }
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.clear();
            values.put(MediaStore.Images.Media.IS_PENDING, 0);
            resolver.update(imageUri, values, null, null);
        }

        return imageUri;
    }
}