通过 Android 中的 WhatsApp 发送信息?


此示例演示了通过 Android 中的 WhatsApp 发送消息

步骤 1 - 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新项目并填写所有必需详细信息以创建一个新项目。

步骤 2 - 将以下代码添加到 res/layout/activity_main.xml 中。

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:orientation = "vertical"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent">
   <TextView
      android:id = "@+id/text"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:text = "click"
      android:textSize = "30sp" />
</LinearLayout>

在上面的代码中,我们使用了文本视图。

步骤 3 - 将以下代码添加到 src/MainActivity.java 中

<?xml version = "1.0" encoding = "utf-8"?>
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
   TextView textView;
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      textView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            PackageManager pm = MainActivity.this.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);
            waIntent.setPackage("com.whatsapp");
            waIntent.putExtra(Intent.EXTRA_TEXT, text);
            startActivity(Intent.createChooser(waIntent, "Share with"));
         } catch (PackageManager.NameNotFoundException e) {
               Toast.makeText(MainActivity.this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
               .show();
            }
         }
      });
   }
}

让我们尝试运行你的应用程序。我认为你已将实际的 Android 移动设备连接到计算机。若要从 Android Studio 运行应用,请打开一个项目的活动文件并单击工具栏中的运行  图标。选择你的移动设备作为选项,然后检查你的移动设备,它将显示你的默认屏幕 -

现在单击文本视图打开 WhatsApp

更新于:2019 年 7 月 30 日

1K+ 浏览量

开启您的职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.