? ? ? ? Android中消息通知主要有兩種方式,一種是簡(jiǎn)短的提示信息,此時(shí)使用Toast,另一種是主動(dòng)推送的信息,應(yīng)使用Notification。
詳細(xì)代碼:Toast ?Notification
1.Toast
toast顯示消息通知時(shí),先makeText,后show,makeText時(shí),參數(shù)為context,顯示的文本內(nèi)容,顯示時(shí)長(zhǎng)
Toast.makeText(MainActivity.this,"顯示一個(gè)較長(zhǎng)的Toast",Toast.LENGTH_LONG).show();
顯示時(shí)長(zhǎng)默認(rèn)只有兩個(gè)值,需要設(shè)置為這兩個(gè)一長(zhǎng)一短的值
Toast.LENGTH_LONG(3.5秒)和Toast.LENGTH_SHORT(2秒)
可依通過(guò)setGravity方法設(shè)置Toast的顯示位置
//后兩個(gè)參數(shù)為x軸和y軸的偏移量,x軸正值向右偏移,y軸正值為向下偏移
aShortToast.setGravity(Gravity.CENTER,100,-200);
可以通過(guò)setView為T(mén)oast設(shè)置圖片,圖片會(huì)取代之前設(shè)置的文本,需要顯示多種內(nèi)容時(shí),自定義layout
Toast imageToast = Toast.makeText(MainActivity.this,"這是一個(gè)帶有圖片的toast",Toast.LENGTH_LONG);
//創(chuàng)建imageView,并設(shè)置圖片源
ImageView iv =newImageView(MainActivity.this);
iv.setImageResource(R.mipmap.ic_launcher);
//為T(mén)oast設(shè)置view
imageToast.setView(iv);
2.Notification
notification,通知,即android狀態(tài)欄頂部的消息推送,
Notification對(duì)象必須包含以下內(nèi)容:
小圖標(biāo),由setSmallIcon()設(shè)置,隱藏時(shí)顯示在狀態(tài)欄頂部
標(biāo)題,由setContentTitle()設(shè)置
詳細(xì)文本,由setContentText()設(shè)置
選擇包含的內(nèi)容
Large icon 大圖標(biāo)
Content info 內(nèi)容信息
通知?jiǎng)?chuàng)建的時(shí)間,由setTime()方法設(shè)置
創(chuàng)建notification之前,先創(chuàng)建builder,通過(guò)builder設(shè)置notification的屬性,用以創(chuàng)建真正的notification
//創(chuàng)建notification前,需要先創(chuàng)建一個(gè)builder,通過(guò)builder創(chuàng)建一個(gè)真正的notification
NotificationCompat.Builder builder =newNotificationCompat
.Builder(MainActivity.this);
通過(guò)builder設(shè)置notification的屬性,小圖標(biāo),標(biāo)題,詳細(xì)文本必須設(shè)置
//通過(guò)builder為當(dāng)前的notification指定屬性
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("你有"+counter+"條新消息!");
builder.setContentText("天空一無(wú)所有,為何給我安慰”);
通過(guò)builde方法,創(chuàng)建notification
//調(diào)用build方法創(chuàng)建notification的真實(shí)對(duì)象
Notification notification = builder.build();
為了在通知欄欄顯示notification,需要通過(guò)notificationManager獲取系統(tǒng)notification服務(wù),
而后通過(guò)manager提示
//獲取系統(tǒng)的notification服務(wù),傳遞給manager用來(lái)在通知欄顯示
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//通過(guò)固定的notificationID對(duì)當(dāng)前的notification進(jìn)行更新,manager進(jìn)行提示
manager.notify(NOTIFICATION_ID,notification);