Sending message through WhatsApp

前端 未结 23 2510
萌比男神i
萌比男神i 2020-11-22 09:42

Since I found some older posts, that tell that whatsapp doesn\'t support this, I was wondering if something had changed and if there is a way to open a whatsapp \'chat\' wit

23条回答
  •  轮回少年
    2020-11-22 10:08

    This works to me:

    public static void shareWhatsApp(Activity appActivity, String texto) {
    
        Intent sendIntent = new Intent(Intent.ACTION_SEND);     
        sendIntent.setType("text/plain");
        sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, texto);
    
        PackageManager pm = appActivity.getApplicationContext().getPackageManager();
        final List matches = pm.queryIntentActivities(sendIntent, 0);
        boolean temWhatsApp = false;
        for (final ResolveInfo info : matches) {
          if (info.activityInfo.packageName.startsWith("com.whatsapp"))  {
              final ComponentName name = new ComponentName(info.activityInfo.applicationInfo.packageName, info.activityInfo.name);
              sendIntent.addCategory(Intent.CATEGORY_LAUNCHER);
              sendIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_TASK);
              sendIntent.setComponent(name);
              temWhatsApp = true;
              break;
          }
        }               
    
        if(temWhatsApp) {
            //abre whatsapp
            appActivity.startActivity(sendIntent);
        } else {
            //alerta - você deve ter o whatsapp instalado
            Toast.makeText(appActivity, appActivity.getString(R.string.share_whatsapp), Toast.LENGTH_SHORT).show();
        }
    }
    

提交回复
热议问题