如何在 android 中的 activity 中创建通知?

How to create notification inside an activity in android?

我有一个任务,我必须在 activity 中显示 Notification 的传入消息,使用 BroadcastReceiver 以及 SMS 上的地址和内容。现在我必须单击才能将 sms 中的值插入到数据库中。任务完成后,我希望它从 activity 中清除。是否可以在 Activity 中为传入的短信创建通知?

您可以试试这个,不要生成您自己的通知。

@SuppressWarnings("deprecation")
private static void generateNotification(Context context) {

    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, "New Contact Added",
            when);

    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context, MainActivity.class);

    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);

    PendingIntent intent = PendingIntent.getActivity(context, iUniqueId,
            notificationIntent, 0);
    notification.setLatestEventInfo(context, title, "New", intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notification.defaults |= Notification.DEFAULT_SOUND;

    // Vibrate if vibrate is enabled
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(2, notification);

}