0

这是我在ActivityOne中发送短信的代码

        private void sendSMS(final String phoneNumber, final String message,final String userMsg)
        {
            String SENT = "SMS_SENT";
            //String DELIVERED = "SMS_DELIVERED";
            PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
            //PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,new Intent(DELIVERED), 0);
            //---when the SMS has been sent---
            registerReceiver(new BroadcastReceiver(){
                @Override   
                public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast toast = Toast.makeText(getApplicationContext(), userMsg, Toast.LENGTH_SHORT);
                        toast.show();

                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getApplicationContext(), "SMS not sent, Generic failure",
                        Toast.LENGTH_SHORT).show();
                    break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getApplicationContext(), "SMS not sent, No service",
                        Toast.LENGTH_SHORT).show();
                    break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getApplicationContext(), "SMS not sent,, Null PDU",
                        Toast.LENGTH_SHORT).show();
                    break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getApplicationContext(), "SMS not sent, Radio off",
                        Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, sentPI, null);

        }

我在 Activity 中这样称呼它:

sendSMS(mobileNumber, "My Message", "SMS sent successfully");

我在下一个活动ActivityTwo中有相同的 sendSMS 方法,但是当我从ActivityTwo发送短信时,它每次都会向我显示最后一个活动ActivityOne的祝酒词。

谢谢。

4

3 回答 3

1

您可以通过添加一个参数并调用 toast 来设置当前上下文,this.context如下所示:

 private void senSMS(final String phoneNumber, final String message,final String userMsg,Context context)
{
//do something
Toast.makeText(context, "SMS sent",Toast.LENGTH_SHORT).show();
}
于 2014-02-18T05:53:15.273 回答
0

如果您有对 Toast 的引用,则可以取消它,但由于它是由单独的活动创建的,因此您无法访问它。

像这样创建它:

Toast toast = Toast.makeText(context, text, duration);

现在您可以通过查看Toast 类toast.cancel()的文档来取消 toast

于 2014-02-18T05:47:04.553 回答
0

注册和注销广播接收器可能存在问题。

如果在 Activity.onResume() 实现中注册接收器,则应在 Activity.onPause() 中取消注册。(暂停时您不会收到意图,这将减少不必要的系统开销)。不要在 Activity.onSaveInstanceState() 中取消注册,因为如果用户移回历史堆栈,则不会调用它。

https://developer.android.com/reference/android/content/BroadcastReceiver.html

于 2014-02-18T06:00:23.317 回答