Android 4.0自定义通知,如谷歌音乐

时间:2012-01-03 12:00:15

标签: android notifications android-4.0-ice-cream-sandwich

我想创建一个带有进度条和删除按钮的自定义通知。

截图:

enter image description here

我成功创建了带有进度条的自定义通知,但我没有设法创建删除事件。我想取消通知并在用户点击“x”后停止上传(如在谷歌音乐中,因此我不想启动活动来清除通知)。

这是我的工作代码:

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

    int icon = R.drawable.ic_launcher;
    CharSequence tickerText = "Hello";
    long when = System.currentTimeMillis();

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


    CharSequence contentTitle = "My notification";
    CharSequence contentText = "Hello World!";
    Intent notificationIntent = new Intent(context, UploadEventsReceiver.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    notification.contentView = new RemoteViews(context.getPackageName(), R.layout.upload_progress);
    notification.contentView.setOnClickPendingIntent(R.id.text, contentIntent);

    notificationManager.notify(this.notificationId, notification);

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

我尝试使用没有“广播”的BroadCast接收器,但我不知道这是否是正确的方法,我没有成功使它工作。我应该使用什么以及如何使用它?

2 个答案:

答案 0 :(得分:5)

我不确定它是如何在Google音乐中制作的,但您可以为传递给RemoteViews的布局中的任何视图设置onClickListener。就这样做:

RemoteViews remoteViews = new RemoteViews(widgetPackage, R.layout.widget);
Intent action = new Intent(context, Your_cancel_broadcast.class);
action.setAction(CANCEL_BROADCAST_ACTION);
actionPendingIntent = PendingIntent.getBroadcast(context, 0, action, 0);
remoteViews.setOnClickPendingIntent(R.id.your_x_btn, actionPendingIntent);

并创建广播,接收CANCEL_BROADCAST_ACTION并停止您想要的内容,并取消此通知。

答案 1 :(得分:0)

另外,我认为(根据文档)您的方法已被弃用。

你应该使用像:

Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("Your notification title");
builder.setContentText("Your notification text");
builder.setSmallIcon(R.drawable.ic_your_icon);
builder.setContentIntent(yourIntent);
notificationManager.notify(null, YOUR_UNIQUE_NOTIFICATION_ID, builder.getNotification());

http://developer.android.com/reference/android/app/NotificationManager.html

http://developer.android.com/reference/android/app/Notification.Builder.html