我正在尝试创建自定义解决方案,以通知SMS Receive。 我在Stackoverflow上找到了一些解决方案,但是它们没有用,任何人都可以帮助我,我错了。以下是我的代码。
public class MainActivity extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast toast = Toast.makeText(context,"Message Received", Toast.LENGTH_LONG);
toast.show();
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My notification")
.setContentText("SMS Received");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, mBuilder.build());
}
}
和清单文件:
<receiver android:name=".MainActivity"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
答案 0 :(得分:0)
试试这个:
<receiver
android:name=".IncomingSmsReceiver"
android:permission="android.permission.BROADCAST_SMS"
android:priority="1000">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
public class IncomingSmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
String messageBody = "no data";
String messageFrom = "no data";
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
messageBody = smsMessage.getMessageBody();
messageFrom = smsMessage.getDisplayOriginatingAddress();
}
Log.d("Sms:", messageBody + " " + messageFrom);
}
}
}