2012-01-03 28 views
5

我想用進度條和刪除按鈕創建自定義通知。Android 4.0自定義通知,如谷歌音樂

截圖:

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

我與廣播接收機嘗試沒有「廣播」,但我不知道這是否是做的正確方法它和我沒有成功,使其工作。我應該使用什麼以及如何使用它?

+0

尼斯,我正要實現我剛纔在你的屏幕截圖發現:整潔的硬件控制切換,例如WiFi,旋轉或飛行模式。你正在運行定製ROM還是你在市場上找到了?感謝您的幫助,祝您的項目順利。 – stfn 2012-01-03 16:48:47

回答

5

我不知道它是如何在谷歌音樂,但你可以設置onClickListener任何視圖中的佈局,傳遞到RemoteViews。只是這樣做:

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並停止你想要什麼,並取消該通知。

+0

這個意圖會被播出嗎?或者將這個意願只發送給我的cancel_broadcast? – Quanturium 2012-01-03 13:10:24

+0

它取決於'CANCEL_BROADCAST_ACTION'的值 - 如果它是自定義的(像「lalala」這樣的smth) - 只有你的廣播會收到這個意圖 – Jin35 2012-01-03 13:28:10

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

+1

注意:Notification.Builder僅在API 11+中可用。 v4支持庫具有NotificationBuilderCompat,但根據以下鏈接,它目前缺少setProgress方法。 http://code.google.com/p/android/issues/detail?id=30755 i – MaximumGoat 2012-07-06 06:35:33