我如何在运行时在我的应用程序中接收短信?

How can i receive SMS in my app in Runtime?

我想在默认短信应用程序接收短信时在我的应用程序中接收短信。我想在收到我的默认短信应用程序时打印该短信。我已经使用这种方法打印了最后收到的短信。

void print_message() throws IOException {
        ActivityCompat.requestPermissions(Objects.requireNonNull(getActivity()), new String[]{Manifest.permission.READ_SMS, Manifest.permission.SEND_SMS}, PackageManager.PERMISSION_GRANTED);

        Cursor cursor = getActivity().getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);

        if (cursor.moveToFirst()) { // must check the result to prevent exception

                String msgData = "";

                    msgData += " " + cursor.getColumnName(2) + ":" + cursor.getString(2) + "\n " + cursor.getColumnName(12) + ":" + cursor.getString(12);
               
                printData(msgData);
        }

        cursor.close();
    }

如何在应用程序 运行 时打印此消息。

试试这个

public class SmsListener extends BroadcastReceiver{

    private SharedPreferences preferences;

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String msg_from;
            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    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]);
                        msg_from = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();
                    }
                }catch(Exception e){
//                            Log.d("Exception caught",e.getMessage());
                }
            }
        }
    }
}

注意:在清单文件中添加 BroadcastReceiver

<receiver android:name=".listener.SmsListener">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

添加此权限:

<uses-permission android:name="android.permission.RECEIVE_SMS" />