如何为代码设置删除意图?

时间:2014-03-31 16:42:28

标签: android service notifications android-notifications

我已多次搜索,但我无法找到我真正需要的东西, stackoverflow上有一些内容,如thisthis 但是我需要为api level 8而不是 11 实现我的代码。那么如何在我的代码中实现它?

我的代码在这里:

....

mNotification = new Notification(icon, tickerText, when);

//create the content which is shown in the notification pulldown
mContentTitle = mContext.getString(R.string.noti_comes_t_l); //Full title of the notification in the pull down
CharSequence contentText = "click to see notification"; //Text of the notification in the pull down

//you have to set a PendingIntent on a notification to tell the system what you want it to do when the notification is selected
//I don't want to use this here so I'm just creating a blank one 
mContentIntent  = PendingIntent.getActivity(mContext, 0, new Intent(mContext, notify.class), 0); 

//add the additional content and intent to the notification
mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent);

//make this notification appear in the 'Ongoing events' section
mNotification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL ;

//show the notification
mNotificationManager.notify(NOTIFICATION_ID, mNotification);

....

我该如何实现?

1 个答案:

答案 0 :(得分:-1)

我认为您需要来自支持库的NotificationCompat,您可以使用此代码生成通知,根据需要进行调整

    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context)
    .setSmallIcon(icon)
    .setContentTitle(context.getString(R.string.app_name))
    .setContentText(message)
            .setDeleteIntent(PendingIntent);

    mBuilder.setWhen(when);

    Intent notificationIntent = new Intent(context, YOURCLASS.class);      
    notificationIntent.putExtra("url", url);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
            Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent intent = PendingIntent.getActivity(context, random, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
    mBuilder.setContentIntent(intent);
    Notification notification = mBuilder.build();

    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(random, notification);