我想开发一个应用程序,以便在收到短信时通知Toast
。通过使用BroadcastReceiver
下面是我的代码:使用广播接收器收到短信时要显示Toast
public class SMSBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "Intent received: " + intent.getAction());
if (intent.getAction().equals(SMS_RECEIVED)) {
Toast.makeText(context, "new incoming message" , Toast.LENGTH_LONG).show();
}
}
}
和清单文件:
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:theme="@style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".SMSBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
</application>
问题既不是Log
也不Toast
被显示。问题在哪里,我应该怎么做?
请在谷歌搜索短信广播。你会解决它:) –
我已经搜查,但没有有用的结果。 –
'telephony'需要在清单中的''''中大写。 ' “android.provider.Telephony.SMS_RECEIVED”'。另外,如果您在Marshmallow +上运行,请确保您正确处理权限。确保安装后至少运行一次'MainActivity'。 –