75

我想知道如何向特定的 whatsapp 联系人发送文本。我找到了一些代码来查看特定联系人,但不能发送数据。

Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
    new String[] { ContactsContract.Contacts.Data._ID }, ContactsContract.Data.DATA1 + "=?",
    new String[] { id }, null);
c.moveToFirst();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));

startActivity(i);
c.close();

这适用于查看whatsapp-contact,但我现在如何添加一些文本?还是 Whatsapp 开发者没有实现这样的 api?

4

29 回答 29

89

我找到了正确的方法来做到这一点:

源代码:phonemessage都是String.

    PackageManager packageManager = context.getPackageManager();
    Intent i = new Intent(Intent.ACTION_VIEW);

    try {
        String url = "https://api.whatsapp.com/send?phone="+ phone +"&text=" + URLEncoder.encode(message, "UTF-8");
        i.setPackage("com.whatsapp");
        i.setData(Uri.parse(url));
        if (i.resolveActivity(packageManager) != null) {
            context.startActivity(i);
        }
    } catch (Exception e){
        e.printStackTrace();
    }

玩的开心!

于 2017-08-22T15:34:14.573 回答
73

我认为答案是您的问题和这里的答案的混合:https ://stackoverflow.com/a/15931345/734687 所以我会尝试以下代码:

  1. 将 ACTION_VIEW 更改为 ACTION_SENDTO
  2. 像你一样设置 Uri
  3. 将包设置为whatsapp
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));
i.setType("text/plain");
i.setPackage("com.whatsapp");           // so that only Whatsapp reacts and not the chooser
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.putExtra(Intent.EXTRA_TEXT, "I'm the body.");
startActivity(i);

我查看了 Whatsapp 清单,发现 ACTION_SEND 已注册到活动ContactPicker中,所以这对您没有帮助。但是 ACTION_SENDTO 已注册到com.whatsapp.Conversation听起来更适合您的问题的活动。

Whatsapp 可以作为发送短信的替代品,所以它应该像短信一样工作。当您没有指定所需的应用程序(通过setPackage)时,Android 会显示应用程序选择器。因此,您应该只查看通过意图发送 SMS 的代码,然后提供额外的包信息。

Uri uri = Uri.parse("smsto:" + smsNumber);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra("sms_body", smsText);  
i.setPackage("com.whatsapp");  
startActivity(i);

首先尝试将意图替换ACTION_SENDACTION_SENDTO. 如果这不起作用,则提供额外的额外sms_body。如果这不起作用,请尝试更改 uri。

更新 我试图自己解决这个问题,但无法找到解决方案。Whatsapp 正在打开聊天记录,但不接收文本并发送。似乎这个功能没有实现。

于 2013-10-04T10:36:52.780 回答
67

我已经做了!

private void openWhatsApp() {
    String smsNumber = "7****"; // E164 format without '+' sign
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");
    sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
    sendIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
    sendIntent.setPackage("com.whatsapp");
    if (intent.resolveActivity(getActivity().getPackageManager()) == null) {
        Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
        return;    
    }
    startActivity(sendIntent);
}
于 2017-02-12T09:53:16.577 回答
22

这种方法也适用于 WhatsApp Business 应用程序!

将包名称更改为 sendIntent.setPackage("com.whatsapp.w4b"); 适用于 WhatsApp 业务。

很棒的 hack Rishabh,非常感谢,我从过去 3 年开始一直在寻找这个解决方案。

根据上面 Rishabh Maurya 的回答,我已经实现了这段代码,它适用于 WhatsApp 上的文本和图像共享。

请注意,在这两种情况下,它都会打开一个 whatsapp 对话(如果用户 whatsapp 联系人列表中存在 toNumber),但用户必须单击发送按钮才能完成操作。这意味着它有助于跳过联系人选择步骤。

对于短信

String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
startActivity(sendIntent);

用于共享图像

String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("image/png");
context.startActivity(sendIntent);

享受WhatsApping!

于 2017-05-16T06:39:54.813 回答
19

它允许您为您尝试与之通信的特定用户打开 WhatsApp 对话屏幕:

private void openWhatsApp() {
    String smsNumber = "91XXXXXXXX20";
    boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");
    if (isWhatsappInstalled) {

        Intent sendIntent = new Intent("android.intent.action.MAIN");
        sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
        sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(smsNumber) + "@s.whatsapp.net");//phone number without "+" prefix

        startActivity(sendIntent);
    } else {
        Uri uri = Uri.parse("market://details?id=com.whatsapp");
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        Toast.makeText(this, "WhatsApp not Installed",
                Toast.LENGTH_SHORT).show();
        startActivity(goToMarket);
    }
}

private boolean whatsappInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    boolean app_installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        app_installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        app_installed = false;
    }
    return app_installed;
}
于 2016-11-18T09:02:27.073 回答
11

查看我的答案:https ://stackoverflow.com/a/40285262/5879376

 Intent sendIntent = new Intent("android.intent.action.MAIN");
 sendIntent.setComponent(new  ComponentName("com.whatsapp","com.whatsapp.Conversation"));
 sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("YOUR_PHONE_NUMBER")+"@s.whatsapp.net");//phone number without "+" prefix

 startActivity(sendIntent);

更新:

前面提到的 hack 不能用于添加任何特定的消息,所以这里是新方法。在此处以国际格式传递用户手机,不带任何括号、破折号或加号。示例:如果用户是印度人并且他的手机号码是94xxxxxxxx,那么国际格式将是9194xxxxxxxx。不要错过在手机号码中附加国家代码作为前缀。

  private fun sendMsg(mobile: String, msg: String){
    try {
        val packageManager = requireContext().packageManager
        val i = Intent(Intent.ACTION_VIEW)
        val url =
            "https://wa.me/$mobile" + "?text=" + URLEncoder.encode(msg, "utf-8")
        i.setPackage("com.whatsapp")
        i.data = Uri.parse(url)
        if (i.resolveActivity(packageManager) != null) {
            requireContext().startActivity(i)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

注意:此方法仅适用于在用户的 Whatsapp 帐户中添加的联系人。

于 2016-10-27T13:09:38.287 回答
11

Whatsapp 有自己的API

    Intent sendIntent = new Intent("android.intent.action.MAIN");
                        sendIntent.setAction(Intent.ACTION_VIEW);
                        sendIntent.setPackage("com.whatsapp");
                        String url = "https://api.whatsapp.com/send?phone=" + "Phone with international format" + "&text=" + "your message";
                        sendIntent.setData(Uri.parse(url));
                        if(sendIntent.resolveActivity(context.getPackageManager()) != null){
                             startActivity(sendIntent);
                        }

为 Activity 添加的代码更新检查是否可用。

请参阅本文档

于 2017-11-27T09:11:32.993 回答
6

这将首先搜索指定的联系人,然后打开一个聊天窗口。如果未安装 WhatsApp,则 try-catch 块处理此问题。

    String digits = "\\d+";
    String mob_num = "987654321";     
    if (mob_num.matches(digits)) 
            {
        try {
              //linking for whatsapp
              Uri uri = Uri.parse("whatsapp://send?phone=+91" + mob_num);
              Intent i = new Intent(Intent.ACTION_VIEW, uri);
              startActivity(i);
            }
            catch (ActivityNotFoundException e){
                    e.printStackTrace();
                    //if you're in anonymous class pass context like "YourActivity.this"
                    Toast.makeText(this, "WhatsApp not installed.", Toast.LENGTH_SHORT).show();
            }
        }
于 2018-01-24T09:44:22.270 回答
6

我正在尝试使用另一个应用程序在 WhatsApp 中发送短信。

假设我们有一个按钮,在按钮上单击您调用下面的方法。

sendTextMsgOnWhatsApp("+91 9876543210", "你好,这是我的测试信息");

public void sendTextMsgOnWhatsApp(String sContactNo, String sMessage) {
        String toNumber = sContactNo; // contains spaces, i.e., example +91 98765 43210
        toNumber = toNumber.replace("+", "").replace(" ", "");

        /*this method contactIdByPhoneNumber() will get unique id for given contact,
        if this return's null then it means that you don't have any contact save with this mobile no.*/
        String sContactId = contactIdByPhoneNumber(toNumber);

        if (sContactId != null && sContactId.length() > 0) {

            /*
             * Once We get the contact id, we check whether contact has a registered with WhatsApp or not.
             * this hasWhatsApp(hasWhatsApp) method will return null,
             * if contact doesn't associate with whatsApp services.
             * */
            String sWhatsAppNo = hasWhatsApp(sContactId);

            if (sWhatsAppNo != null && sWhatsAppNo.length() > 0) {
                Intent sendIntent = new Intent("android.intent.action.MAIN");
                sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
                sendIntent.putExtra(Intent.EXTRA_TEXT, sMessage);
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.setPackage("com.whatsapp");
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
            } else {
                // this contact does not exist in any WhatsApp application
                Toast.makeText(this, "Contact not found in WhatsApp !!", Toast.LENGTH_SHORT).show();
            }
        } else {
            // this contact does not exist in your contact
            Toast.makeText(this, "create contact for " + toNumber, Toast.LENGTH_SHORT).show();
        }
    }

    private String contactIdByPhoneNumber(String phoneNumber) {
        String contactId = null;
        if (phoneNumber != null && phoneNumber.length() > 0) {
            ContentResolver contentResolver = getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            String[] projection = new String[]{ContactsContract.PhoneLookup._ID};

            Cursor cursor = contentResolver.query(uri, projection, null, null, null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
                }
                cursor.close();
            }
        }
        return contactId;
    }

    public String hasWhatsApp(String contactID) {
        String rowContactId = null;
        boolean hasWhatsApp;

        String[] projection = new String[]{ContactsContract.RawContacts._ID};
        String selection = ContactsContract.RawContacts.CONTACT_ID + " = ? AND " + ContactsContract.RawContacts.ACCOUNT_TYPE + " = ?";
        String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
        Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
        if (cursor != null) {
            hasWhatsApp = cursor.moveToNext();
            if (hasWhatsApp) {
                rowContactId = cursor.getString(0);
            }
            cursor.close();
        }
        return rowContactId;
    }

在AndroidManifest.xml文件中添加以下权限

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
于 2019-10-14T12:26:31.300 回答
4

这是最短的方法

    String mPhoneNumber = "+972505555555";
    mPhoneNumber = mPhoneNumber.replaceAll("+", "").replaceAll(" ", "").replaceAll("-","");
    String mMessage = "Hello world";
    String mSendToWhatsApp = "https://wa.me/" + mPhoneNumber + "?text="+mMessage;
    startActivity(new Intent(Intent.ACTION_VIEW,
            Uri.parse(
                    mSendToWhatsApp
            )));

另请参阅 WhatsApp 的文档

于 2018-08-27T17:50:44.863 回答
4
try {
                    String text = "Hello, Admin sir";// Replace with your message.

                    String toNumber = "xxxxxxxxxxxx"; // Replace with mobile phone number without +Sign or leading zeros, but with country code
                    //Suppose your country is India and your phone number is “xxxxxxxxxx”, then you need to send “91xxxxxxxxxx”.


                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + toNumber + "&text=" + text));
                    context.startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));

                }
于 2019-05-22T15:26:11.383 回答
3

这现在可以通过WhatsApp Business API实现。只有企业可以申请使用它。这是直接向电话号码发送消息的唯一方法,无需任何人工交互。

发送普通消息是免费的。看起来您需要在服务器上托管 MySQL 数据库和 WhatsApp Business Client。

于 2018-08-28T06:59:01.407 回答
2

您还可以选择 WhatsApp 业务与 WhatsApp

String url = "https://api.whatsapp.com/send?phone=" + phoneNumber + "&text=" + 
  URLEncoder.encode(messageText, "UTF-8");
  if(useWhatsAppBusiness){
    intent.setPackage("com.whatsapp.w4b");
  } else {
    intent.setPackage("com.whatsapp");
  }
  URLEncoder.encode(messageText, "UTF-8");
  intent.setData(Uri.parse(url));

  if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent);
  } else {
    Toast.makeText(this, "WhatsApp application not found", Toast.LENGTH_SHORT).show();
  }
于 2020-10-08T17:30:40.697 回答
1

试试这个,为我工作!. 只需使用意图

   Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(whatsappUrl()));
   startActivity(intent);

建立whatsapp网址。在 whatsapp 电话号码中添加国家代码https://countrycode.org/

public static String whatsappUrl(){

    final String BASE_URL = "https://api.whatsapp.com/";
    final String WHATSAPP_PHONE_NUMBER = "628123232323";    //'62' is country code for Indonesia
    final String PARAM_PHONE_NUMBER = "phone";
    final String PARAM_TEXT = "text";
    final String TEXT_VALUE = "Hello, How are you ?";

    String newUrl = BASE_URL + "send";

    Uri builtUri = Uri.parse(newUrl).buildUpon()
            .appendQueryParameter(PARAM_PHONE_NUMBER, WHATSAPP_PHONE_NUMBER)
            .appendQueryParameter(PARAM_TEXT, TEXT_VALUE)
            .build();

    return buildUrl(builtUri).toString();
}

public static URL buildUrl(Uri myUri){

    URL finalUrl = null;
    try {
        finalUrl = new URL(myUri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();

    }
    return finalUrl;
}
于 2017-08-24T09:51:46.127 回答
1
 private void openWhatsApp() {
       //without '+'
        try {
            Intent sendIntent = new Intent("android.intent.action.MAIN");

            //sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.setType("text/plain");
            sendIntent.putExtra("jid",whatsappId);
            sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            sendIntent.setPackage("com.whatsapp");
            startActivity(sendIntent);
        } catch(Exception e) {
            Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
            Log.e("Error",e+"")    ;    }
    }
于 2017-11-06T13:02:53.653 回答
1

在 Python 中,您可以像使用移动应用程序一样进行操作

 web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)

这将预先填充给定手机号码的文本(输入 phone_no 作为 CountryCode 和号码,例如 +918888888888)然后使用pyautogui您可以按 enter 进入 whatsapp.web

工作代码:

def sendwhatmsg(phone_no, message, time_hour, time_min):
     '''Sends whatsapp message to a particulal number at given time'''
     if time_hour == 0:
         time_hour = 24
     callsec = (time_hour*3600)+(time_min*60)

     curr = time.localtime()
     currhr = curr.tm_hour
     currmin = curr.tm_min
     currsec = curr.tm_sec

     currtotsec = (currhr*3600)+(currmin*60)+(currsec)
     lefttm = callsec-currtotsec

     if lefttm <= 0:
         lefttm = 86400+lefttm

     if lefttm < 60:
         raise Exception("Call time must be greater than one minute")

     else:
         sleeptm = lefttm-60
         time.sleep(sleeptm)
         web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)
         time.sleep(60)
         pg.press('enter')

我从这个存储库中获取了这个 - Github repo

于 2019-12-15T03:07:56.023 回答
1

这段代码是用 Kotlin 实现的。

我有 2 个版本:

1) 对于已知联系人

private fun openWhatsApp(dato: WhatsApp) {
    val isAppInstalled = appInstalledOrNot("com.whatsapp")
    if (isAppInstalled) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://api.whatsapp.com/send?phone=${dato.whatsapp}"))
        startActivity(intent)
    } else {
        // WhatsApp not installed show toast or dialog
    }
}

private fun appInstalledOrNot(uri: String): Boolean {
    val pm = requireActivity().packageManager
    return try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES)
        true
    } catch (e: PackageManager.NameNotFoundException) {
        false
    }
}

如果是未知联系人,WhatsApp 会显示以下消息

在此处输入图像描述

2) 对于未知联系人

private fun openWhatsApp(dato: WhatsApp) {
    val isAppInstalled = appInstalledOrNot("com.whatsapp")
    if (isAppInstalled) {
        val sendIntent = Intent("android.intent.action.MAIN")
        sendIntent.setType("text/plain")
        sendIntent.setComponent(ComponentName("com.whatsapp", "com.whatsapp.Conversation"))
        sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(dato.whatsapp) + "@s.whatsapp.net")
        startActivity(sendIntent)
    } else {
        // WhatsApp not installed show toast or dialog
    }
}

private fun appInstalledOrNot(uri: String): Boolean {
    val pm = requireActivity().packageManager
    return try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES)
        true
    } catch (e: PackageManager.NameNotFoundException) {
        false
    }
}
于 2020-01-08T18:25:29.883 回答
1

这是一种如何在 KOTLIN 的 WhatsApp 中发送消息的方法

    private fun sendMessage(phone: String, message: String) {
        val pm = requireActivity().packageManager
        val i = Intent(Intent.ACTION_VIEW)
        try {
            val url = "https://api.whatsapp.com/send?phone=$phone&text=" + URLEncoder.encode(
                message,
                "UTF-8"
            )
            i.setPackage("com.whatsapp")
            i.data = Uri.parse(url)
            if (i.resolveActivity(pm) != null) {
                context?.startActivity(i)
            }
        } catch (e: PackageManager.NameNotFoundException) {
            Toast.makeText(requireContext(), "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
        }
    }
于 2020-06-25T08:00:57.257 回答
1

2020 年更新

     String number="+91 7*********";
            String url="https://api.whatsapp.com/send?phone="+number + "&text=" + "Your text here";
            Intent i=new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
于 2020-11-18T07:57:33.817 回答
1

以编程方式向特定联系人发送文本(Whatsapp)

try {
    val i = Intent(Intent.ACTION_VIEW)
    val url = "https://api.whatsapp.com/send?phone=91XXXXXXXXXX&text=yourmessage"
    i.setPackage("com.whatsapp")
    i.data = Uri.parse(url)
    startActivity(i)
} catch (e: Exception) {
   e.printStackTrace()
   val uri = Uri.parse("market://details?id=com.whatsapp")
   val goToMarket = Intent(Intent.ACTION_VIEW, uri)
   startActivity(goToMarket)
}
于 2021-02-15T06:40:24.007 回答
0

检查这个答案。在这里,您的号码以“91**********”开头。

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_SEND);

sendIntent.setType("text/plain");                    
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");                   sendIntent.putExtra("jid",PhoneNumberUtils.stripSeparators("91**********")                   + "@s.whatsapp.net");                    
sendIntent.setPackage("com.whatsapp");                    
startActivity(sendIntent);
于 2017-06-03T10:58:44.470 回答
0

这将首先搜索指定的联系人,然后打开一个聊天窗口。

注意:phone_numberstr是变量。

Uri mUri = Uri.parse("https://api.whatsapp.com/send?
phone=" + phone_no + "&text=" + str);
Intent mIntent = new Intent("android.intent.action.VIEW", mUri);
mIntent.setPackage("com.whatsapp");
startActivity(mIntent);
于 2017-09-21T20:18:21.413 回答
0
Bitmap bmp = null;
            bmp = ((BitmapDrawable) tmpimg.getDrawable()).getBitmap();
            Uri bmpUri = null;
            try {
                File file = new File(getBaseContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".jpg");
                FileOutputStream out = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.close();
                bmpUri = Uri.fromFile(file);

            } catch (IOException e) {
                e.printStackTrace();
            }

            String toNumber = "+919999999999"; 
            toNumber = toNumber.replace("+", "").replace(" ", "");
            Intent shareIntent =new Intent("android.intent.action.MAIN");
            shareIntent.setAction(Intent.ACTION_SEND);
            String ExtraText;
            ExtraText =  "Share Text";
            shareIntent.putExtra(Intent.EXTRA_TEXT, ExtraText);
            shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            shareIntent.setType("image/jpg");
            shareIntent.setPackage("com.whatsapp");
            shareIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {

                startActivity(shareIntent);
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(getBaseContext(), "Sharing tools have not been installed.", Toast.LENGTH_SHORT).show();
            }

        }
于 2018-06-02T03:19:19.180 回答
0
private void sendToContactUs() {
     String phoneNo="+918000874386";

    Intent sendIntent = new Intent("android.intent.action.MAIN");
    sendIntent.setAction(Intent.ACTION_VIEW);
    sendIntent.setPackage("com.whatsapp");
    String url = "https://api.whatsapp.com/send?phone=" + phoneNo + "&text=" + "Unique Code - "+CommonUtils.getMacAddress();
    sendIntent.setDataAndType(Uri.parse(url),"text/plain");


    if(sendIntent.resolveActivity(getPackageManager()) != null){
        startActivity(sendIntent);
    }else{
        Toast.makeText(getApplicationContext(),"Please Install Whatsapp Massnger App in your Devices",Toast.LENGTH_LONG).show();
    }
}
于 2019-03-15T17:15:47.550 回答
0

 public void shareWhatsup(String text) {


        String smsNumber = "91+" + "9879098469"; // E164 format without '+' sign

        Intent intent = new Intent(Intent.ACTION_VIEW);

        try {
            String url = "https://api.whatsapp.com/send?phone=" + smsNumber + "&text=" + URLEncoder.encode(text, "UTF-8");
            intent.setPackage("com.whatsapp");
            intent.setData(Uri.parse(url));
        } catch (Exception e) {
            e.printStackTrace();
        }

        //    intent.setAction(Intent.ACTION_SEND);
        //   intent.setType("image/jpeg");
        //   intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUriArray);
        startActivity(intent);


    }

于 2019-04-01T11:04:49.480 回答
0

而不是偏向于将内容分享到什么应用程序。

下面的代码是一个通用代码,它将使用“ShareCompact”提供一个简单的解决方案,android 打开支持共享内容的应用程序列表。

这里我分享的是 mime 类型 text/plain 的数据。

    String mimeType = "text/plain"
    String Message  = "Hi How are you doing?"

    ShareCompact.IntentBuilder
                .from(this)
                .setType(mimeType)
                .setText(Message)
                .startChooser()
于 2019-08-19T09:23:44.947 回答
0

Whatsapp 和大多数其他集成到 Android 核心组件(如联系人)的应用程序使用基于 mime 类型的意图来启动应用程序中的某个 Activity。Whatsapp 使用 3 种不同的 mimetypes - 短信 (vnd.android.cursor.item/vnd.com.whatsapp.profile)、voip 通话 (vnd.android.cursor.item/vnd.com.whatsapp.voip.call) 和视频通话(vnd.android.cursor.item/vnd.com.whatsapp.video.call)。对于这些 mimetype 中的每一个,在应用程序的 Manifest 中映射了一个单独的活动。例如:mimetype (...whatsapp.profile) 映射到 Activity (com.whatsapp.Conversation)。如果您转储映射到联系人数据库中任何 Whatsapp Raw_Contact 的所有数据行,您可以详细查看这些内容。

这也是 Android 联系人应用程序在“Whatsapp 联系人”中显示 3 行单独的用户操作的方式,单击其中任一行会在 Whatsapp 中启动单独的功能。

要在 Whatsapp 中为某个联系人启动对话(聊天)活动,您需要触发包含 MIME_TYPE 和 DATA_URL 的意图。mimetype 指向与您在 Whatsapp 的联系人数据库中的原始联系人中定义的操作相对应的 mimetype。DATA_URL 是 Android 联系人数据库中 Raw_Contact 的 URI。

String whatsAppMimeType = Uri.parse("vnd.android.cursor.item").buildUpon()
                                    .appendEncodedPath("vnd.com.whatsapp.profile").build().toString();

Uri uri = ContactsContract.RawContacts.CONTENT_URI.buildUpon()
        .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.whatsapp")
        .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, "WhatsApp")
        .build();

Cursor cursor = getContentResolver().query(uri, null, null, null);
if (cursor==null || cursor.getCount()==0) continue;

cursor.moveToNext();
int rawContactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.RawContacts._ID));
cursor.close();

// now search for the Data row entry that matches the mimetype and also points to this RawContact
Cursor dataCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
        null,
        ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.Data.RAW_CONTACT_ID + "=?",
        new String[]{whatsAppMimeType, String.valueOf(rawContactId)}, null);
if (dataCursor==null || dataCursor.getCount()==0) continue;

dataCursor.moveToNext();
int dataRowId = dataCursor.getInt(dataCursor.getColumnIndex(ContactsContract.Data._ID));

Uri userRowUri = ContactsContract.Data.CONTENT_URI.buildUpon()
                        .appendPath(String.valueOf(dataRowId)).build();


// launch the whatsapp user chat activity
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(userRowUri, whatsAppMimeType);
startActivity(intent);

dataCursor.close();

这与所有联系人应用程序用于为 Whatsapp 联系人启动聊天活动的方式相同。在这个 Activity 中,应用程序 (Whatsapp) 读取 .getData() 以获取传递给这个 Activity 的 DATA_URI。Android 联系人应用程序使用标准机制来使用 Whatsapp 中原始联系人的 URI。不幸的是,我不知道 Whatsapp 中的 .Conversation 活动从意图调用者那里读取任何文本/数据信息的方式。这基本上意味着它可以(使用非常标准的技术)在 Whatsapp 中启动某个“用户操作”。或者就此而言,任何类似的应用程序。

于 2019-09-26T22:52:49.627 回答
0

使用此功能。在发送触发功能之前,不要忘记将 WhatsApp 号码保存在您的手机上。

private void openWhatsApp() {
        Uri uri = Uri.parse("smsto:"+ "12345");
        Intent i = new Intent(Intent.ACTION_SENDTO,uri);
        i.setPackage("com.whatsapp");
        startActivity(i);
    }
于 2020-07-20T11:51:31.997 回答
0

以下将打开 Whatsapp 对话(与联系人)页面并用提供的文本预填充它。注意:这不会自动将文本发送到 Whatsapp 服务器。它只会打开对话页面。用户需要明确按下“发送”按钮才能真正将文本发送到服务器。

String phoneId = "+1415xxxyyyy"; // the (Whatsapp) phone number of contact 
String text = "text to send";

Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
sendIntent.putExtra("jid", phoneId);
sendIntent.setPackage("com.whatsapp"); 
startActivity(sendIntent);
于 2021-06-19T18:10:19.657 回答