本文實例講述了android不使用自定義布局情況下實現(xiàn)自定義通知欄圖標的方法。分享給大家供大家參考,具體如下:
自定義通知欄圖標?不是很簡單么。自定義布局都不在話下!
是的,有xml布局文件當然一切都很簡單,如果不給你布局文件用呢?
聽我慢慢道來!
首先怎么創(chuàng)建一個通知呢?
1.new 一個
參數(shù):圖標 id,發(fā)送到狀態(tài)欄瞬間的文字,當前時間
2.設置詳細信息:標題、內(nèi)容、intent
1
2
|
pendingintent contentintent = pendingintent.getbroadcast( this , 0 , intent, pendingintent.flag_update_current); n.setlatesteventinfo( this , "早上好!" , "今天是個晴朗的天氣!" , contentintent); |
3.發(fā)送到通知欄
1
2
|
notificationmanager mnm = (notificationmanager) getsystemservice(context.notification_service); mnm.notify( 1001 , n); |
這樣就完成了一個通知的展示,很簡單!
我們來看看 n.setlatesteventinfo 干了些什么呢
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public void setlatesteventinfo(context context, charsequence contenttitle, charsequence contenttext, pendingintent contentintent) { // todo: rewrite this to use builder remoteviews contentview = new remoteviews(context.getpackagename(), r.layout.notification_template_base); if ( this .icon != 0 ) { contentview.setimageviewresource(r.id.icon, this .icon); } if (priority < priority_low) { contentview.setint(r.id.icon, "setbackgroundresource" , r.drawable.notification_template_icon_low_bg); contentview.setint(r.id.status_bar_latest_event_content, "setbackgroundresource" , r.drawable.notification_bg_low); } if (contenttitle != null ) { contentview.settextviewtext(r.id.title, contenttitle); } if (contenttext != null ) { contentview.settextviewtext(r.id.text, contenttext); } if ( this .when != 0 ) { contentview.setviewvisibility(r.id.time, view.visible); contentview.setlong(r.id.time, "settime" , when); } if ( this .number != 0 ) { numberformat f = numberformat.getintegerinstance(); contentview.settextviewtext(r.id.info, f.format( this .number)); } this .contentview = contentview; this .contentintent = contentintent; } |
可以看到,他實際上就是使用系統(tǒng)默認布局為我們創(chuàng)建了一個 remoteviews ,remoteviews 是專門用來跨進程顯示的 view ,詳情參考官方文檔:http://developer.android.com/intl/zh-cn/reference/android/widget/remoteviews.html
看這句:
其實就是設置圖標了:
參數(shù)1:用來顯示圖標的 imageview 的 id
參數(shù)2:圖標 id
但是還有一個這樣的方法:
用 bitmap 來設置圖標。
而 notifycation 里面有個參數(shù):notification.contentview,仔細看,setlastesteventinfo 方法里創(chuàng)建的 remoteviews 就是他,所以你知道該怎么做了!
但是這里還有一個問題?r.id.icon 怎么獲取,這個東西其實在 com.android.internal.r 這個里面,但是這個類我們訪問不到怎么辦?
反射唄, java 的反射可謂是萬能啊,啥都可以拿到只要他在。
1
2
3
4
|
class <?> clazz = class .forname( "com.android.internal.r$id" ); field field = clazz.getfield( "icon" ); field.setaccessible( true ); int id_icon = field.getint( null ); |
1
2
3
4
5
|
n.setlatesteventinfo(context, title, msg, contentintent); n.flags |= notification.flag_auto_cancel; if (n.contentview != null && icon != null ){ n.contentview.setimageviewbitmap(id_icon, icon); } |
發(fā)出通知,下拉通知欄看看,圖標是不是變了^_^
此外這里還有一個小細節(jié),就是你 new notifycation() 是傳進去的圖標會作為狀態(tài)欄的小圖標,小圖標尺寸在 hdpi 下面放 32x32 的就可以
所以你可以第一次傳小圖標,然后通過 contentview 設置大圖標,這樣就ok了
希望本文所述對大家android程序設計有所幫助。