因此,我正在尝试编写一个将发送SMS消息,接收并查看已发送消息的应用程序。到目前为止,我可以发送消息,但是接收消息在API 26上不起作用。我的下一个仿真器是API 21,并且在该版本上,当收到消息时,会显示Toast消息。
我已经成功管理了发送和接收短信的权限。
我已经阅读了一些文档,但是找不到我需要的东西。如果有人知道问题出在哪里,我将非常感谢您的帮助。
公共类SmsReceiver扩展了BroadcastReceiver {
private static final String TAG = "SmsReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
String message = "";
for(int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
if(i == 0) {
message += messages[i].getOriginatingAddress() + ": ";
}
message += messages[i].getMessageBody();
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
}
}
清单文件
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver android:name="package.name"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
我希望这足够了,如果需要的话,我可以提供其他类或清单文件。预先感谢
答案 0 :(得分:0)
您必须使用以下伪代码在运行时获得用户的许可:
public static void requestPermissionForReadSMS(Fragment fragment) {
if (fragment.shouldShowRequestPermissionRationale(Manifest.permission.READ_SMS)) {
Helpers.showRequestPermissionAlertDialog(fragment, fragment.getString(R.string.read_sms_permission), fragment.getString(R.string.permission_request));
} else {
fragment.requestPermissions(new String[]{Manifest.permission.RECEIVE_SMS},
Constants.READ_SMS_PERMISSION);
}
}
之后,您的BroadcastReceiver将正常工作
您还可以将BROADCAST_SMS添加到清单中的接收者标签中:
<receiver android:name="packagename.SmsReceiver"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter
android:priority="4876123720">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
此外,您还可以阅读有关官方文档中提供的“ SMS Retriever” api巫婆,用于在您的应用程序中接收短信
答案 1 :(得分:-1)
我完全没有回答我的问题。产生错误行为的错误与接收消息的意图有关。我以为我可以使用相同的意图来打印已发送的消息和接收消息。最后,当我创建用于接收短信的自定义意图并成功时。