我试图在我的Android应用中实现推送通知。理想情况下,如果打开了首选项,则当新消息到达时,屏幕顶部应显示我的自定义标题和图标的通知。但是当我收到新消息时没有任何反应。我正在运行模拟器(因为我没有带SIM卡的设备)来发送和接收消息,版本是Android 5.0.1,API 21。
这是我的通知代码:
public class SmsReceiver extends BroadcastReceiver {
private static String TAG = "**SmsReceiver**";
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final int NOTIFY_CODE = 1;
private static final int NOTIFY_ID = 3;
private static int SMS_SENT_CODE = 2;
final SmsManager sms = SmsManager.getDefault();
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Received SMS: " + intent);
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
// notifications and auto-reply
for (SmsMessage message : messages) {
notification(context, message);
}
}
}
}
private void notification(Context context, SmsMessage message) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// determine whether to push notification or not
boolean pushNotification = prefs.getBoolean("pref_push_notification",true);
if (pushNotification) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("New Message from: "+message.getDisplayOriginatingAddress())
.setContentText(message.getDisplayMessageBody())
.setVibrate(new long[] {0,500,500,500})
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setPriority(NotificationCompat.PRIORITY_HIGH);
Intent resultIntent = new Intent(context, MainActivity.class);
// add a history stack from the parent stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(NOTIFY_CODE,PendingIntent.FLAG_UPDATE_CURRENT);
// handle click notification
builder.setContentIntent(pendingIntent);
// ask the system whether to show notification
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFY_ID,builder.build());
}
else {
Toast.makeText(context,"You got a message", Toast.LENGTH_SHORT).show();
}
}
有什么错误的想法?提前谢谢!