如何从另一个活动中调用whatApp意图?

时间:2018-09-08 07:24:38

标签: android android-intent whatsapp

我已经在这个问题上挣扎了2天,有人可以提出解决建议吗?

这是我的WhatsApp2活动...

public class WhatsApp2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
public void whatsappSend(){
    try {
        String toNumber = "xxxxxxxxxx";
        Intent sendIntent = new Intent(Intent.ACTION_SENDTO,    Uri.parse("smsto:" + "" + toNumber+ "?body=" + ""));
        sendIntent.setPackage("com.whatsapp");
        startActivity(sendIntent);
    }
    catch (Exception e){
        e.printStackTrace();
    }
  }
}

我正试图从另一个活动中调用whatsappSend()……

public class MainActivity extends  AppCompatActivity {
    public WhatsApp2 whatsApp2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 }

 public void whatsapp(View view) {
     whatsApp2 = new WhatsApp2();
     whatsApp2.whatsappSend();
  }
 }

Catch在WhatsApp2类中的异常错误为:

  

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.app.ActivityThread $ ApplicationThread android.app.ActivityThread.getApplicationThread()'

1 个答案:

答案 0 :(得分:-1)

**Try this if you want call whatsapp method from another activity**
//MainActivity



public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
        Whatspp send=new Whatspp(this);
        send.whatsappSend();
    }



}
//Whatspp Class

public class Whatspp  {
    Context _cContext;

    public Whatspp(MainActivity mainActivity) {
        _cContext=mainActivity;
    }

    void whatsappSend() {
        try {
            String toNumber = "**********";
            Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + "" + toNumber + "?body=" + ""));
            sendIntent.setPackage("com.whatsapp");
            _cContext.startActivity(sendIntent);
        } catch (Exception e) {
            Log.i("TAG", "whatsappSend: "+e.getMessage());
            e.printStackTrace();
        }

    }
}