參考
Android 通知欄Notification的整合 全面學(xué)習(xí) (一個DEMO讓你完全了解它)
Android中Notification的PendingIntent無效問題解決
android的Notifications的例子demo
一、概念
- 拿到NotificationManager
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- 創(chuàng)建Notification
Notification notification = new Notification( R.drawable.icon,"This is ticket text",System.currentTimeMillis());
第一個參數(shù)用于指定通知圖標(biāo)。第二個參數(shù)用于指定通知的ticker內(nèi)容,當(dāng)通知剛被創(chuàng)建時(shí),會在狀態(tài)欄一閃而過。第三個參數(shù)指定通知創(chuàng)建時(shí)間,當(dāng)下拉系統(tǒng)狀態(tài)欄時(shí),這個時(shí)間會顯示在相應(yīng)的通知上。 - 指定通知的實(shí)際標(biāo)題和內(nèi)容。
notification.setLatestEventInfo(context,"This is content title","This is content text",null);
- 發(fā)出通知
manager.notify(1,notification);//第一個參數(shù)表示通知id不能重復(fù)
- 點(diǎn)擊通知跳轉(zhuǎn)到NotificationActivity
使用延時(shí)執(zhí)行的intent,即PendingIntent
Intent intent = new Intent(this,NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context,"This is content title","This is content text",pi);//第四個參數(shù)
manager.notify(1,notification);
- 打開NotificationActivity時(shí),要關(guān)閉通知欄。
public class NotificationActivity extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_layout);
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
manager.cancel(1);//nofify中第一個參數(shù)使用的id
}
}
- 為通知加上聲音和振動,LED閃爍
可以直接使用通知的默認(rèn)效果notification.defaults = Notificaion.DEFAULT_ALL;
Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/Basic_tone.ogg"));
notification.sound = soundUri;
long[] vibrates = {0,1000,1000,1000};//靜止時(shí)長,振動時(shí)長,靜止時(shí)長……
notification.vibrate = vibrate;
notification.ledARGB = Color.GREEN;
notification.ledOnMS = 1000;//亮起時(shí)長
notification.ledOffMS = 1000;//暗去時(shí)長
notification.flags = Notificaion.FLAG_SHOW_LIGHTS;
二、 新版本變化
參考Android技巧小結(jié)之新舊版本Notification
在較新的版本中(API level > 11),Notification類中的一些方法被Android聲明deprecated(棄用),其實(shí)基本上相當(dāng)于全部棄用了。
1.初始化
private Notification note;
//API 11以下
note = new Notification(R.drawable.ico_launcher ,
"顯示于屏幕頂端狀態(tài)欄的文本", System.currentTimeMillis());
//API 11及以上
Notification.Builder builder = new Notification.Builder(nowContext)
.setTicker("顯示于屏幕頂端狀態(tài)欄的文本")
.setSmallIcon(R.drawable.ic_laucher);
//API 11以上版本中,狀態(tài)欄顯示的樣式跟下拉通知欄中顯示的樣式,可以
//一起設(shè)置,就是通過Notification.Builder類來實(shí)現(xiàn),這里的Builder只
//調(diào)用了兩個方法來設(shè)置狀態(tài)欄顯示樣式。
2、設(shè)置Notification在通知欄里的樣式
(1)系統(tǒng)默認(rèn)樣式
//API 11以下:
note.setLatestEventInfo(nowContext, "take me to your heart", "Micheal learn to rock", pendingIntent);
//API 16及以上,build()方法要求API 16及以上
//一會API 11以上,一會API16以上,我也很想知道Android的API是怎么設(shè)計(jì)的
note = builder.setContentIntent(pendingIntent).setContentTitle("title").setContentText("text").build();
(2)自定義樣式:
自定義樣式,就是讓Notification在通知欄顯示成自定義的xml布局.應(yīng)當(dāng)注意的是,Notification的自定義樣式,只支持以下可視組件:
FrameLayout, LinearLayout, RelativeLayout.TextView, Button, AnalogClock, ImageView, ImageButton, Chronometer, ProgressBar
RemoteView view = new RemoteView(nowActivity.getPackageName(), R.layout.note_layout);
//API 11以下
note.contentView = view;
note.contentIntent = pendingIntent;
//API 16及以上,又是build()方法導(dǎo)致的,汗。。
note = builder.setContent(view).setContentIntent(pendingIntent).build();
這個步驟里有一個很值得注意的地方:pendingIntent被設(shè)置為note的contentIntent的值,就意味著點(diǎn)擊了這個通知才會觸發(fā)該Intent。
那么如果只是想讓自定義布局里的某個按鈕觸發(fā)呢?比如說,弄了一個音樂播放器,Service負(fù)責(zé)播放音樂,Notification顯示當(dāng)前播放進(jìn)度和一些簡單的暫停按鈕、上一首、下一首按鈕,讓用戶不用再打開界面就可以通過Notification上的按鈕操縱音樂播放。假設(shè)說想讓自定義布局里的一個id為R.id.button1的按鈕來觸發(fā)這個Intent,可以如下操作:
view.setOnClickPendingIntent(R.id.button1, pendingIntent);
//在上面創(chuàng)建RemoteView實(shí)例后加上這句
然后注意,pendingIntent已經(jīng)綁定到按鈕上了,上面Notificatiion實(shí)例中,設(shè)置contentIntent的語句要去掉。
三、簡單例子
參考
Android通知Notification入門小例子(一)
package com.demo.notificationdemo;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button start_notification;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start_notification = (Button) findViewById(R.id.start_notification);
start_notification.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.start_notification:
/**
* 創(chuàng)建通知管理類NotificationManager的實(shí)例,用來管理通知
*/
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/**
* 創(chuàng)建通知類Notification實(shí)例(用來存儲通知所需的信息); 一共三個參數(shù):
* 1)、指定通知使用的圖標(biāo),如:R.drawable.ic_launcher ;
* 2)、指定通知的ticker內(nèi)容,通知被創(chuàng)建的時(shí)候,在狀態(tài)欄一閃而過,屬于瞬時(shí)提示信息。
* 3)、指定通知被創(chuàng)建的時(shí)間,以毫秒為單位,下拉狀態(tài)欄時(shí),這個時(shí)間會顯示在相應(yīng)的通知上。
*/
Notification notification = new Notification(
R.drawable.ic_launcher, "有通知來了", System.currentTimeMillis());
/**
* 實(shí)例化Intent,構(gòu)建意圖:從當(dāng)前頁面跳轉(zhuǎn)到NotificationActivity頁面
*/
Intent intent = new Intent(this, NotificationActivity.class);
/**
* 用于啟動活動、啟動服務(wù)以及發(fā)送廣播等。 根據(jù)需求來選擇是使用
* getActivity()方法、getBroadcast()方法、還是 getService() 方法。 一共四個參數(shù):
* 1)、第一個參數(shù)是 上下文Context ; 2)、 第二個參數(shù)一般用不到,通常都是傳入 0 即可 3)、第三個參數(shù)是一個
* Intent對象,我們可以通過這個對象構(gòu)建出 PendingIntent 的“意圖”; 4)、第四個參數(shù)用于確定
* PendingIntent 的行為
*/
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
/**
* 設(shè)定通知標(biāo)準(zhǔn)的布局。四個參數(shù): 1)、上下文對象Context; 2)、指定通知的標(biāo)題內(nèi)容,下拉系統(tǒng)狀態(tài)欄可看到;
* 3)、指定通知的正文,下拉系統(tǒng)狀態(tài)欄可看到; 4)、用于啟動活動、啟動服務(wù)以及發(fā)送廣播
*/
notification.setLatestEventInfo(this, "股票大漲", "今日萬科的股票停牌,應(yīng)對惡意收購",
pendingIntent);
/**
* 啟動通知. 兩個參數(shù): 1)、id,保證每個通知的id唯一; 2)、Notification對象
*/
manager.notify(1, notification);
break;
default:
break;
}
}
}
package com.demo.notificationdemo;
import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
public class NotificationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_text);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//cancel()方法中的參數(shù)是我們在啟動通知,調(diào)用manager.notify(1, notification)方法時(shí),傳的id
manager.cancel(1);//取消系統(tǒng)狀態(tài)欄上的通知圖標(biāo)
}
}
四、自定義通知RemoteViews
參考Android自定義Notification并沒有那么簡單
RemoteViews表示的是一個View結(jié)構(gòu),它可以在其他進(jìn)程中(系統(tǒng)的SystemServer進(jìn)程)顯示,為了能夠更新它的界面,RemoteViews提供了一組基礎(chǔ)操作用于跨進(jìn)程更新。
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.tickerText = "hello world";
notification.when = System.currentTimeMillis();
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, DemoActivity_1.class);
intent.putExtra("sid", "" + sId);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
System.out.println(pendingIntent);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);
//無法直接訪問view,必須通過setTextViewText設(shè)置id和要設(shè)置的文本
remoteViews.setTextViewText(R.id.msg, "chapter_5: " + sId);
//設(shè)置ImageView的圖片
remoteViews.setImageViewResource(R.id.icon, R.drawable.icon1);
PendingIntent openActivity2PendingIntent = PendingIntent.getActivity(this,0, new Intent(this, DemoActivity_2.class), PendingIntent.FLAG_UPDATE_CURRENT);
//給一個控件添加單擊事件
remoteViews.setOnClickPendingIntent(R.id.open_activity2, openActivity2PendingIntent);
notification.contentView = remoteViews;
notification.contentIntent = pendingIntent;
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(sId, notification);
1.折疊式通知 使用bigContentView
// 通過RemoteViews來創(chuàng)建自定義的Notification視圖
RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.notification);
contentView.setTextViewText(R.id.textView,"show me when collapsed");
Notification notification = builder.build();
notification.contentView = contentView;
// 通過RemoteViews來創(chuàng)建自定義的Notification視圖
RemoteViews expandedView = new RemoteViews(getPackageName(),R.layout.notification_expanded);
notification.bigContentView = expandedView;
//可以做版本判斷
//if(Build.VERSION.SDK_INT >= 16){
// notification.bigContentView = rvMain;
//}
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID_COLLAPSE, notification);
2.懸掛式通知 使用setFullScreenIntent
android5.0新增加的方式,可以在屏幕上方產(chǎn)生通知且不打斷用戶操作
public void headsupNotify(View view) {
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setPriority(Notification.PRIORITY_DEFAULT)
.setCategory(Notification.CATEGORY_MESSAGE)
.setContentTitle("Headsup Notification")
.setContentText("I am a Headsup notification.");
Intent push = new Intent();
push.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
push.setClass(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, push, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentText("Heads-Up Notification on Android 5.0")
.setFullScreenIntent(pendingIntent, true);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID_HEADSUP, builder.build());
}
3.顯示等級的通知 使用setVisibility
public void visibilityNotify(View view) {
RadioGroup radioGroup = (RadioGroup) findViewById(
visibility_radio_group);
Notification.Builder builder = new Notification.Builder(this)
.setContentTitle("Notification for Visibility Test");
switch (radioGroup.getCheckedRadioButtonId()) {
case R.id.radio_button_public:
//任何情況下都顯示通知
builder.setVisibility(Notification.VISIBILITY_PUBLIC);
builder.setContentText("Public");
builder.setSmallIcon(R.drawable.ic_public);
break;
case R.id.radio_button_private:
//只有當(dāng)沒鎖屏?xí)r顯示
builder.setVisibility(Notification.VISIBILITY_PRIVATE);
builder.setContentText("Private");
builder.setSmallIcon(R.drawable.ic_private);
break;
case R.id.radio_button_secret:
//在pin,password等安全鎖和沒有鎖屏的情況下才顯示
builder.setVisibility(Notification.VISIBILITY_SECRET);
builder.setContentText("Secret");
builder.setSmallIcon(R.drawable.ic_secret);
break;
}
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID_VISIBILITY, builder.build());
}
e