Send message to specific number whatsapp android?

2019-08-02 15:43发布

问题:

How can I send message to specific number in whatsapp.

I searched and found this code

 Uri uri = Uri.parse("smsto:" + number);
    Intent i = new Intent(Intent.ACTION_SENDTO, uri);
    i.putExtra("sms_body", "as sdj ajs");
    i.setPackage("com.whatsapp");
    startActivity(i);

It only opens that number's chat window but no message is displayed in the edit text.

Also tried this

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

    startActivity(i);
    c.close();

But it force closes the app

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
        at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
        at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
        at android.database.CursorWrapper.getString(CursorWrapper.java:114)
        at com.appprix.app.AppLauncher.whatsappShare(AppLauncher.java:113)
        at appprix.refer.ReferFragment.onClick(ReferFragment.java:74)
        at android.view.View.performClick(View.java:4575)
        at android.view.View$PerformClick.run(View.java:18578)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5127)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
        at dalvik.system.NativeStart.main(Native Method)

回答1:

do this way

public void onClickWhatsApp(View view) {

    PackageManager pm=getPackageManager();
    try {

        Intent waIntent = new Intent(Intent.ACTION_SEND);
        waIntent.setType("text/plain");
        String text = "YOUR TEXT HERE";

        PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
        //Check if package exists or not. If not then code 
        //in catch block will be called
        waIntent.setPackage("com.whatsapp");

            waIntent.putExtra(Intent.EXTRA_TEXT, text);
            startActivity(Intent.createChooser(waIntent, "Share with"));

   } catch (NameNotFoundException e) {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
   }  

}