以编程方式将文本发送到特定联系人(whatsapp)

时间:2013-09-29 18:24:33

标签: android android-intent contact whatsapp

我想知道如何将文字发送到特定的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?

28 个答案:

答案 0 :(得分:62)

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

  1. 将ACTION_VIEW更改为ACTION_SENDTO
  2. 像你一样设置Uri
  3. 将包设置为whatsapp
  4. 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_SEND替换为ACTION_SENDTO。如果这不起作用,则提供额外的额外sms_body。如果这不起作用,请尝试更改uri。

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

答案 1 :(得分:52)

我做到了!

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

答案 2 :(得分:48)

我找到了正确的方法,这很简单,你只需阅读这篇文章:http://howdygeeks.com/send-whatsapp-message-unsaved-number-android/

源代码: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();
    }

享受!

答案 3 :(得分:15)

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

将包名更改为sendIntent.setPackage(“com.whatsapp.w4b”);为WhatsApp业务。

很棒的黑客Rishabh,非常感谢,自从过去3年以来我一直在寻找这个解决方案。

根据Rishabh Maurya上面的回答,我已经实现了这个代码,该代码在WhatsApp上的文本和图像共享都很好。

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

用于短信

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!

答案 4 :(得分:14)

它允许您为您尝试与之通信的特定用户打开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;
}

答案 5 :(得分:10)

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

<div ng-repeat="emoji in emojis">
  {{ addEmojiTest(emoji.code) }}
</div>

答案 6 :(得分:6)

这将首先搜索指定的联系人,然后打开聊天窗口。 如果没有安装WhatsApp,那么try-catch阻止处理这个。

 String digits = "\\d+";
    Sring 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();
                    Toast.makeText(this, "WhatsApp not installed.", Toast.LENGTH_SHORT).show();
            }
        }

答案 7 :(得分:3)

这是最短的方法

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

See also the documentation of WhatsApp

答案 8 :(得分:2)

这里正在尝试通过其他应用程序在WhatsApp中发送短信。

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

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" />

答案 9 :(得分:2)

现在可以通过WhatsApp Business API来实现。仅企业可以申请使用它。 这是直接将消息发送到电话号码而无需任何人工干预的唯一方法。

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

答案 10 :(得分: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()
    }
}

答案 11 :(得分:0)

您还可以选择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();
  }

答案 12 :(得分: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);
    }

答案 13 :(得分:0)

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

答案 14 :(得分:0)

<块引用>

以编程方式向特定联系人发送文本 (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)
}

答案 15 :(得分:0)

此代码由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将显示以下消息

enter image description here

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
    }
}

答案 16 :(得分:0)

在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

答案 17 :(得分: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);

答案 18 :(得分:0)

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

这也是Android Contacts应用程序在“ Whatsapp联系人”中显示3条单独的用户操作行的方式,然后单击这些行中的任一行将在Whatsapp内部启动单独的功能。

要为Whatsapp中的某个联系人启动对话(聊天)活动,您需要激发一个包含MIME_TYPE和DATA_URL的意图。模仿类型指向与您在Whatsapp的“联系人中的原始联系人”数据库​​中定义的操作相对应的模仿类型。 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 Atfinity如何从意图调用者中读取任何文本/数据信息。这基本上意味着,有可能(使用非常标准的技术)在Whatsapp内部启动特定的“用户操作”。或与此相关的任何类似应用。

答案 19 :(得分:0)

与其偏向与Whats App共享内容。

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

我在这里共享mime型文本/纯文本的数据。

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

    ShareCompact.IntentBuilder
                .from(this)
                .setType(mimeType)
                .setText(Message)
                .startChooser()

答案 20 :(得分:0)

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

                }

答案 21 :(得分: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);


    }

答案 22 :(得分:0)

a = pd.DataFrame([[0,1,2],[3,4,5],[4,5,6],[9,10,11],[34,2,1]])
a.index = [0, 1, 2, 3.1, 4]  # add a float index

# value based slicing: the following will output all value up to the slice value
a.loc[1:3.1]
# Out:
# 0    1   2
# 1.0  3   4   5
# 2.0  4   5   6
# 3.1  9  10  11

# index based slicing: will raise an error, since only integers are allowed
a.iloc[1:3.1]
# Out: TypeError: cannot do slice indexing on <class 'pandas.core.indexes.numeric.Float64Index'> with these indexers [3.2] of <class 'float'>

答案 23 :(得分: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();
            }

        }

答案 24 :(得分:0)

 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+"")    ;    }
    }

答案 25 :(得分:0)

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

注意: phone_number str 是变量。

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

答案 26 :(得分:0)

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

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

答案 27 :(得分: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);