如何在android中的活动内创建通知?

时间:2015-06-08 12:34:45

标签: android notifications

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

1 个答案:

答案 0 :(得分:0)

您可以尝试此操作,不要生成您自己的通知。

@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);

}