-1

我想从我们的应用程序发送和接收短信并且发送成功,但接收在我的代码的 SmsMessage 类中显示弃用,这由我在网络上的网站演示。所以,我想要一种不被弃用的 SMS 接收接收方法。请向我建议正确的解决方案。

接收代码:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = "";            
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
                str += "SMS from " + msgs[i].getOriginatingAddress();                     
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                         
    }
}
4

2 回答 2

3

import android.telephony.gsm.SmsMessage;

以上应改为:

import android.telephony.SmsMessage;

于 2012-04-06T03:09:25.937 回答
1

将 BROADCAST_SMS 权限添加到您的接收器,并使启用和导出为 true:

<receiver android:name="com.mohamedtest.sendandreceivesms_m.SMSReceiver"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.BROADCAST_SMS">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
    </receiver>
于 2021-03-06T14:27:53.587 回答