目标和编译 SDK 版本 23+ 时无法在 Marshmallow 中接收短信

Can't receive SMS in Marshmallow when target & compile sdk version 23+

我正在尝试使用 marshmallow nexus 设备中的广播接收器接收短信。 我正在使用目标和编译 SDK 版本 23。我知道使用低于 23 的目标 SDK 版本可行,但我不喜欢该解决方案。如果有使用目标 SDK 版本 23+ 在 marshmallow 中读取 SMS 的方法,请回答。

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(SmsReceiver.class.getSimpleName(), "SMS received");
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hello_receive_sms.app" >
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="com.example.hello_receive_sms.app.SmsReceiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.example.hello_receive_sms.app"
        minSdkVersion 9
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

您需要获得许可。对于 api 级别 23+,google 重新设计了权限系统,以便应用用户可以在安装您的应用后授予和撤销权限。

在清单中设置权限只是第一步。你应该阅读一些关于 "runtime permissions in android marshmallow":

http://developer.android.com/training/permissions/requesting.html