首页 > 解决方案 > 将应用程序 apk 和短信发送到 WhatsApp 的代码

问题描述

我想在 Android 中编写一个代码,可以将应用程序的.apk文件和短信发送到 WhatsApp。我应该怎么做?
这是我的代码的基本框架:

package com.example.testapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

标签: androidbuttoninvite

解决方案


谷歌:从应用程序向whatsapp发送消息

public void openWhatsApp(View view){
    PackageManager pm=getPackageManager();
    try {
        Intent waIntent = new Intent(Intent.ACTION_SEND);
        waIntent.setType("text/plain");
        String text = "This is  a Test"; // Replace with your own message.

        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 (PackageManager.NameNotFoundException e) {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
    }catch(Exception e){
        e.printStacktrace();
    }

}


推荐阅读