我正在尝试使用以下代码以编程方式发送WhatsApp消息。
void openWhatsappContact(String number, Context context) {
Uri uri = Uri.parse("smsto:" + number);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.setPackage("com.whatsapp");
i.putExtra(Intent.EXTRA_TEXT, "test");
context.startActivity(Intent.createChooser(i, ""));
}
每次成功调用此帮助程序函数(我通过记录它来检查),但无法发送消息。显然,startActivity(来自日志)都出错了。发布日志以供参考。
10-20 15:59:34.029: W/System.err(16336): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
10-20 15:59:34.029: W/System.err(16336): at android.app.ContextImpl.startActivity(ContextImpl.java:847)
10-20 15:59:34.029: W/System.err(16336): at android.content.ContextWrapper.startActivity(ContextWrapper.java:276)
10-20 15:59:34.029: W/System.err(16336): at android.content.ContextWrapper.startActivity(ContextWrapper.java:276)
10-20 15:59:34.029: W/System.err(16336): at com.scimet.admin.driveon.RejectCall.openWhatsappContact(RejectCall.java:79)
10-20 15:59:34.029: W/System.err(16336): at com.scimet.admin.driveon.RejectCall.onReceive(RejectCall.java:63)
10-20 15:59:34.029: W/System.err(16336): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2139)
10-20 15:59:34.029: W/System.err(16336): at android.app.ActivityThread.access$1500(ActivityThread.java:127)
10-20 15:59:34.029: W/System.err(16336): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
10-20 15:59:34.029: W/System.err(16336): at android.os.Handler.dispatchMessage(Handler.java:99)
10-20 15:59:34.029: W/System.err(16336): at android.os.Looper.loop(Looper.java:137)
10-20 15:59:34.029: W/System.err(16336): at android.app.ActivityThread.main(ActivityThread.java:4441)
10-20 15:59:34.029: W/System.err(16336): at java.lang.reflect.Method.invokeNative(Native Method)
10-20 15:59:34.029: W/System.err(16336): at java.lang.reflect.Method.invoke(Method.java:511)
10-20 15:59:34.029: W/System.err(16336): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-20 15:59:34.029: W/System.err(16336): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-20 15:59:34.029: W/System.err(16336): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
添加 -
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
答案 1 :(得分:0)
尝试以下代码
try {
Intent intent= new Intent(Intent.ACTION_SEND);
intent.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
intent.setPackage("com.whatsapp");
intent.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(intent, "Share with"));
} catch (NameNotFoundException e) {
Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
.show();
}