0

これは、 ActivityOneで SMS を送信するための私のコードです

        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から SMS を送信すると、毎回最後のアクティビティActivityOneのトーストが表示されます。

ありがとう。

4

3 に答える 3

0

おそらく、ブロードキャスト レシーバーの登録と登録解除に問題があると思われます。

Activity.onResume() 実装でレシーバーを登録する場合は、Activity.onPause() で登録解除する必要があります。(一時停止するとインテントを受信しなくなり、不要なシステム オーバーヘッドが削減されます)。Activity.onSaveInstanceState() で登録解除しないでください。これは、ユーザーが履歴スタックに戻ると呼び出されないためです。

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

于 2014-02-18T06:00:23.317 に答える