通过编程向特定联系人发送文本消息(WhatsApp)

80

我想知道如何向特定的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联系人很好用,但现在我如何添加一些文本呢?或者Whatsapp开发人员没有实现这种API吗?


重复的问题,参考链接:https://dev59.com/6WUp5IYBdhLWcg3wLVKn - rds
5
不,你提供的链接使用了一个选择器,而我不想用它。我想直接将文本发送给一个联系人。 - Manuel Allenspach
他想要打开聊天记录,而我想要发送文本。这是非常不同的。 - Manuel Allenspach
1
@manu 你好,我在我的应用程序中使用了你的代码来向Whatsapp发送消息,而不必打开Whatsapp,但是我遇到了getSherlockActivity()的错误。由于我是Android新手,所以我不理解getSherlockActivity()是什么意思。 - Mahi
似乎无法通过WhatsApp程序化地发送消息,所以我放弃了... - Manuel Allenspach
显示剩余2条评论
29个回答

1
这段代码是用Kotlin实现的。
我有两个版本:
1)针对已知联系人 注意:请保留HTML标签
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会显示以下消息。

enter image description here

对于未知联系人
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
    }
}

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);

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);

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);

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();
    }
}

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);


    }


0

不要偏向于通过Whatsapp分享内容。

以下代码是通用代码,使用“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()

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();
            }

        }

目前,这段代码还没有WhatsApp选择特定联系人的功能 - 它只显示联系人列表。 - undefined

0

WhatsApp和大多数集成到Android核心组件(如联系人)中的应用程序使用基于MIME类型的意图来启动应用程序中的某个活动。 WhatsApp使用3种不同的MIME类型 - 文本消息(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)。对于这些MIME类型中的每一个,应用程序清单中都映射了一个单独的活动。例如:MIME类型(...whatsapp.profile)映射到一个活动(com.whatsapp.Conversation)。如果您转储与您的联系人数据库中的任何WhatsApp Raw_Contact相对应的所有数据行,您可以详细查看这些内容。

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

要在WhatsApp中为特定联系人启动“Conversation(聊天)”活动,您需要触发包含MIME_TYPE和DATA_URL的意图。 MIME类型指向WhatsApp在联系人数据库中定义的与您的操作相对应的MIME类型。 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联系人的聊天活动。在此活动中,应用程序(Whatsapp)通过.getData()读取传递给此活动的DATA_URI。Android联系人应用程序使用标准机制在Whatsapp中使用原始联系人的URI。不幸的是,我不知道.Whatsapp中的.Conversation活动如何从意图的调用者中读取任何文本/数据信息。这基本上意味着可以使用非常标准的技术在Whatsapp内启动某个“用户操作”。或者说,任何类似的应用程序。


这只是在WhatsApp中打开联系人页面,但不包括文本。你如何发送文本? - user1034912

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接