我想开发一个应用程序,以便在收到sms消息时通过Toast
通知我。下面使用BroadcastReceiver
是我的代码:
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
。问题在哪里,我该怎么办?
答案 0 :(得分:0)
public class SmsReceiver extends BroadcastReceiver {
private String TAG = SmsReceiver.class.getSimpleName();
public SmsReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// Get the data (SMS data) bound to intent
Bundle bundle = intent.getExtras();
if (bundle != null) {
// Retrieve the SMS Messages received
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage msgs = new SmsMessage[pdus.length];
//YOUR TOAST
}
}
您可以从msgs
并在清单文件中
<receiver
android:name=".broadcast.SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
实时应用中的工作文件。 希望这会有所帮助..
答案 1 :(得分:-1)
我一直在为我的短信收发器使用以下代码:
<receiver android:name=".SMSBroadcastReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>