uid 没有 android.permission.SEND_SMS

uid does not have android.permission.SEND_SMS

我正在尝试从一个模拟器向另一个模拟器发送消息 (SMS):

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="eheio.com.exo2">

    <uses-permission android:name="android.permission.SEND_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">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

发送消息方式:

public void sendMessage(View view) {
        EditText number = findViewById(R.id.number);
        EditText message = findViewById(R.id.message);
        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(number.getText().toString(), null, message.getText().toString(), null, null);
            Toast.makeText(getApplicationContext(), "SMS Sent!", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "SMS failed, please try again later!", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

我遇到以下异常:

java.lang.SecurityException: Sending SMS message: uid 10082 does not have android.permission.SEND_SMS.

对于初学者,您可以检查授予您的应用程序的权限,方法是:

adb shell dumpsys package <your package>

你会看到如下内容:

grantedPermissions:
  android.permission.MANAGE_ACCOUNTS
  android.permission.WRITE_SYNC_SETTINGS
  android.permission.RECEIVE_BOOT_COMPLETED

android.permission.SEND_SMS权限为dangerous保护级别。这意味着从 API 23 开始,您需要提示用户接受许可。仅在清单中声明其用途是不够的。你可以在这里阅读: https://developer.android.com/guide/topics/permissions/overview#dangerous-permission-prompt

android.permission.SEND_SMS为危险防护等级。所以在清单中声明 <uses-permission android:name="android.permission.SEND_SMS"/> 是不够的。 因此,在 API 级别 23 以上,当应用程序为 运行.

时,您需要提示用户接受权限

您可以试试下面的代码:

SmsManager smsManager = SmsManager.getDefault();
ActivityCompat.requestPermissions(this,new String[] { Manifest.permission.SEND_SMS}, 1);
smsManager.sendTextMessage(strPhoneNo, null, strMessage, null, null);