1. 程式人生 > >Android開發之使用Notification.Builder

Android開發之使用Notification.Builder

通知的主要功能是提示功能。例如:簡訊、推送資訊等等。


大體使用步驟:

1.獲取狀態通知欄管理

NotificationManager 是一個系統Service,所以必須通過 getSystemService(NOTIFICATION_SERVICE)方法來獲取。

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

2.例項化通知欄構造器NotificationCompat.Builder

3.設定NotificationCompat.Builder

4.設定PendingIntent

5.顯示

方法或引數介紹:

1.PendingIntent

PendingIntent.getBroadcast(context, requestCode, intent, flags)

PendingIntent.getActivities(context, requestCode, intents, flags)

PendingIntent.getService(context, requestCode, intent, flags)

中的flags屬性引數:

FLAG_ONE_SHOT   表示返回的PendingIntent僅能執行一次,執行完後自動取消

FLAG_NO_CREATE     表示如果描述的PendingIntent不存在,並不建立相應的PendingIntent,而是返回NULL

FLAG_CANCEL_CURRENT      表示相應的PendingIntent已經存在,則取消前者,然後建立新的PendingIntent

FLAG_UPDATE_CURRENT     表示更新的PendingIntent

2.notification.flags引數介紹

Notification.FLAG_SHOW_LIGHTS              //三色燈提醒,在使用三色燈提醒時候必須加該標誌符

Notification.FLAG_ONGOING_EVENT          //發起正在執行事件(活動中)

Notification.FLAG_INSISTENT   //讓聲音、振動無限迴圈,直到使用者響應 (取消或者開啟)

Notification.FLAG_ONLY_ALERT_ONCE  //發起Notification後,鈴聲和震動均只執行一次

Notification.FLAG_AUTO_CANCEL      //使用者單擊通知後自動消失

Notification.FLAG_NO_CLEAR          //只有全部清除時,Notification才會清除 ,不清楚該通知(QQ的通知無法清除,就是用的這個)

Notification.FLAG_FOREGROUND_SERVICE    //表示正在執行的服務

使用方法:

在設定完屬性後,設定

Notification notification =builder.build();
notification.flags =Notification.FLAG_ONLY_ALERT_ONCE;

3.setVibrate(long[] pattern)

設定震動,需要許可權.

<uses-permission android:name="android.permission.VIBRATE"/> 


4.builder.setOngoing( )

設定為ture,表示它為一個正在進行的通知。簡單的說,當為ture時,不可以被側滑消失。

***************************************************************************************

使用自定義Notification,就要使用RemoteViews。

***************************************************************************************

使用例項:

圖片:

   

實現程式碼:

MainActivity.java

public class MainActivity extends Activity {

	Button button, button2;
	NotificationManager notificationManager;
	public final static String NEWS_LISTEN = "broadcast";

	// 用於自定義Notification,點選事件的驗證
	String remoteViewsText = "未點選";

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

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

		IntentFilter filter = new IntentFilter();
		filter.addAction(NEWS_LISTEN);
		this.registerReceiver(broadcastReceiver, filter);

	}

	public void click(View v) {

		switch (v.getId()) {
		case R.id.but:// 使用普通的Notification

			Notification.Builder builder = new Notification.Builder(
					MainActivity.this);

			Intent intent = new Intent(MainActivity.this, SecondActivity.class);
			PendingIntent pendingIntent = PendingIntent.getActivity(
					MainActivity.this, 0, intent,
					PendingIntent.FLAG_UPDATE_CURRENT);

			builder.setContentIntent(pendingIntent);
			builder.setSmallIcon(R.drawable.close);// 設定圖示
			builder.setWhen(System.currentTimeMillis());// 設定通知來到的時間
			// builder.setAutoCancel(true);
			builder.setContentTitle("標題");// 設定通知的標題
			builder.setContentText("內容");// 設定通知的內容
			builder.setTicker("狀態列上顯示");// 狀態列上顯示
			builder.setOngoing(true);

			/*
			 * // 設定聲音(手機中的音訊檔案) String path =
			 * Environment.getExternalStorageDirectory() .getAbsolutePath() +
			 * "/Music/a.mp3"; File file = new File(path);
			 * builder.setSound(Uri.fromFile(file));
			 */

			// 獲取Android多媒體庫內的鈴聲
			builder.setSound(Uri.withAppendedPath(
					Audio.Media.INTERNAL_CONTENT_URI, "5"));

			// builder.setVibrate(new long[]{2000,1000,4000}); //需要真機測試
			Notification notification = builder.build();
			// notification.flags =Notification.FLAG_ONGOING_EVENT;

			notificationManager.notify(0, notification);

			break;

		case R.id.but2:// 使用自定義的Notification
			// 3.0之前不支援Button
			MyNotification();

			break;

		case R.id.but3:// 使用下載的Notification,在4.0以後才能使用

			final Notification.Builder builder3 = new Notification.Builder(
					MainActivity.this);
			builder3.setSmallIcon(R.drawable.ic_launcher)
					.setTicker("showProgressBar").setContentInfo("contentInfo")
					.setOngoing(true).setContentTitle("ContentTitle")
					.setContentText("ContentText");
			// 模擬下載過程
			new Thread(new Runnable() {
				@Override
				public void run() {

					int progress = 0;

					for (progress = 0; progress < 100; progress += 5) {
						// 將setProgress的第三個引數設為true即可顯示為無明確進度的進度條樣式
						builder3.setProgress(100, progress, false);

						notificationManager.notify(0, builder3.build());
						try {
							Thread.sleep(1 * 1000);
						} catch (InterruptedException e) {
							System.out.println("sleep failure");
						}
					}
					builder3.setContentTitle("Download complete")
							.setProgress(0, 0, false).setOngoing(false);
					notificationManager.notify(0, builder3.build());

				}
			}).start();

			break;
		case R.id.but4:// 大布局通知在4.1以後才能使用,BigTextStyle

			Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
			textStyle.setBigContentTitle("大標題")
					// 標題
					.setSummaryText("SummaryText")
					.bigText(
							"Big Text!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
									+ "!!!!!!!!!!!"
									+ "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");// 內容
			Notification.Builder builder2 = new Notification.Builder(
					MainActivity.this);
			builder2.setSmallIcon(R.drawable.icon);// 小圖示
			// 大圖示
			builder2.setLargeIcon(BitmapFactory.decodeResource(
					this.getResources(), R.drawable.close));
			builder2.setTicker("showBigView_Text")
					.setContentInfo("contentInfo");
			builder2.setStyle(textStyle);
			builder2.setAutoCancel(true);

			notificationManager.notify(0, builder2.build());

			break;

		case R.id.but5://大布局通知在4.1以後才能使用,大布局圖片
			
			Notification.BigPictureStyle bigPictureStyle = new Notification.BigPictureStyle();
			bigPictureStyle.bigPicture(BitmapFactory.decodeResource(getResources(), R.drawable.back));
			
			Notification.Builder builder4 = new Notification.Builder(
					MainActivity.this);
			builder4.setSmallIcon(R.drawable.icon);// 小圖示
			// 大圖示
			builder4.setLargeIcon(BitmapFactory.decodeResource(
					this.getResources(), R.drawable.close));
			builder4.setTicker("showBigView_Picture")
					.setContentInfo("contentInfo");
			builder4.setStyle(bigPictureStyle);
			builder4.setAutoCancel(true);

			notificationManager.notify(0, builder4.build());
			
			break;
			
		case R.id.but6://大布局通知在4.1以後才能使用,InboxStyle
			
			Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
			inboxStyle.setBigContentTitle("InboxStyle");
			inboxStyle.setSummaryText("Test");
			for(int i =0 ;i<5;i++){
				inboxStyle.addLine("new:"+i);
			}
			
			Notification.Builder builder5 = new Notification.Builder(
					MainActivity.this);
			builder5.setSmallIcon(R.drawable.icon);// 小圖示
			// 大圖示
			builder5.setLargeIcon(BitmapFactory.decodeResource(
					this.getResources(), R.drawable.close));
			builder5.setTicker("showBigView_InboxStyle")
					.setContentInfo("contentInfo");
			builder5.setStyle(inboxStyle);
			builder5.setAutoCancel(true);

			notificationManager.notify(0, builder5.build());
			
			
			break;

		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 取消廣播接收
		this.unregisterReceiver(broadcastReceiver);
	}

	/**
	 * 自定義Notification
	 */
	public void MyNotification() {

		RemoteViews remoteViews = new RemoteViews(getPackageName(),
				R.layout.form);
		remoteViews.setTextViewText(R.id.tv_form, remoteViewsText);

		Intent intent2 = new Intent(MainActivity.NEWS_LISTEN);

		// 使用廣播,所以INTENT必須用getBroadcast方法
		PendingIntent pendingIntent2 = PendingIntent.getBroadcast(
				MainActivity.this, 1, intent2,
				PendingIntent.FLAG_UPDATE_CURRENT);

		// 繫結
		remoteViews.setOnClickPendingIntent(R.id.but_form, pendingIntent2);

		Notification.Builder builderMain = new Notification.Builder(
				MainActivity.this);

		builderMain
				.setContent(remoteViews)
				.setSmallIcon(R.drawable.icon)
				.setLargeIcon(
						BitmapFactory.decodeResource(this.getResources(),
								R.drawable.open)).setOngoing(true)
				.setTicker("music is playing");
		notificationManager.notify(0, builderMain.build());
	}

	// 廣播接收器(自定義Notification使用到)
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context c, Intent intent) {

			if (intent.getAction().equals(NEWS_LISTEN)) {

				remoteViewsText = "已點選";
				MyNotification();

			}
		}
	};
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <Button
        android:id="@+id/but"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="notification one" />

    <Button
        android:id="@+id/but2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="notification two" />

    <Button
        android:id="@+id/but3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="notification three" />

    <Button
        android:id="@+id/but4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="notification four" />

    <Button
        android:id="@+id/but5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="notification five" />

    <Button
        android:id="@+id/but6"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="notification six" />

</LinearLayout>

form.xml(自定義通知的樣式)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/but_form"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="嘻嘻" />
    
    
    <TextView 
        android:id="@+id/tv_form"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="無"/>

</LinearLayout>


SecondActivity.java 只是一個activity。

相關推薦

Android開發使用Notification.Builder

通知的主要功能是提示功能。例如:簡訊、推送資訊等等。 大體使用步驟: 1.獲取狀態通知欄管理 NotificationManager 是一個系統Service,所以必須通過 getSystemService(NOTIFICATION_SERVICE)方法來獲取。 not

Android開發getX,getRawX,getWidth,getTranslationX等的區別

save string hlist getwidth sta 是我 touch 項目 寬度 轉載請註明出處:http://blog.csdn.net/dmk877/article/details/51550031 好久沒寫博客了,最近工作確實挺忙的,剛剛結束了一個

Android 開發Windows環境下Android Studio安裝和使用教程(圖文詳細步驟)

9.png 虛擬機 jdk版本 編寫 clip 開發平臺 集成開發 arc 電腦安裝 鑒於谷歌最新推出的Android Studio備受開發者的推崇,所以也跟著體驗一下。 一、介紹Android Studio Android Studio 是一個Android

Android開發AudioManager(音頻管理器)具體解釋

應該 數量 service eth out 開發 要求 type 路由 AudioManager簡單介紹: AudioManager類提供了訪問音量和振鈴器mode控制。使用Context.getSystemService(Context.AUDIO_SERVICE)

【入門篇】ANDROID開發BUG專講

world 自然 執行 類型 效率 str 積累 全部 href 話說諸葛亮是一個優秀的程序員,每個錦囊都是應對不同的case而編寫的。可是優秀的程序員也敵只是更優秀的bug。六出祈山。七進中原,鞠躬盡瘁,死而後已的諸葛亮僅僅由於有一

android開發merge結合include優化布局

ted com match clas you title example ews 文件的 merge結合include優化android布局,效果不知道。個人感覺使用上也有非常大的局限。只是還是了解一下。記錄下來。 布局文件都要有根節點,但androi

Android開發增量更新

avt exp chm 這一 font ams extern city ron 一、使用場景 apk升級,節省服務器和用戶的流量 二、原理 自從 Android 4.1 開始, Google Play 引入了應用程序的增量更新功能,App使用該升級方式,可節省約2/3

Android開發布局文件裏實現OnClick事件關聯處理方法

intent dsm nbsp ext 關聯 you vertica findview 時間 一般監聽OnClickListener事件,我們都是通過Button button = (Button)findViewById(....); button.se

Android 開發 ---- bootloader (LK)

ttl tab 不同的 opera 指定 isa system void mem LK是什麽 LK 是 Little Kernel 它是 appsbl (Applications ARM Boot Loader)流程代碼 ,little kernel

Android開發藍牙連接打印機

cep sdi tco disable ner gis util receiver count 代碼很簡單,直接一個布局文件和一個activity。需要的朋友可以直接將這兩部分粘貼復制到項目中即可。 Activity部分: package com.anhua.bluet

Android開發新建項目報錯的問題

instr rul txt gin 通過 ini .com org top 通過android studio新建一個空項目。在新建完項目之後,gradle編譯會報錯。 發生問題的原因是build.gradle(Project:TopDialog)中: allproject

Android開發CriminalIntent項目開發(其一)

開發項目 1.0 enc 增加 委派 其他 date 應用 module 前言   這次的開發項目是一個叫做CriminalIntent的應用,該應用可以詳細記錄各種辦公室陋習。這個應用記載的陋習記錄包括標題、日期和圖片,支持在聯系人中查找當事人,通過E-mail、Twit

Android開發旅3:android架構

通過 圖集 例如 sqlit 組件 mil 大小 簡化 .html 引言 通過前面兩篇: Android 開發之旅:環境搭建及HelloWorld Android 開發之旅:HelloWorld項目的目錄結構 我們對android有了個大

Android開發旅1:環境搭建及HelloWorld

lan 及其 其它 ply 新項目 bsp 驗證 for 對話框 ——工欲善其事必先利其器 引言 本系列適合0基礎的人員,因為我就是從0開始的,此系列記錄我步入Android開發的一些經驗分享,望與君共勉!作為Android隊伍中的一個新人的

Android開發漫漫長途 番外篇——自定義View的各種姿勢2

是個 pub water 常用 getchild mod one 它的 sdn 該文章是一個系列文章,是本人在Android開發的漫漫長途上的一點感想和記錄,我會盡量按照先易後難的順序進行編寫該系列。該系列引用了《Android開發藝術探索》以及《深入理解Android 卷

Android開發漫漫長途 番外篇——內存泄漏分析與解決

set 程序 靜態 內存 ins clas back undle 介紹 該文章是一個系列文章,是本人在Android開發的漫漫長途上的一點感想和記錄,我會盡量按照先易後難的順序進行編寫該系列。該系列引用了《Android開發藝術探索》以及《深入理解Android 卷Ⅰ,Ⅱ,

2017.12.18 Android開發消息隊列(實現子線程修改UI組件)

nds ace text read exce xtend prot ktr sta 1.界面布局,以及組件初始化: 組件初始化: private Button button; private Handler handler; @Ove

Android開發漫漫長途 Ⅷ——Android Binder(也許是最容易理解的)

pct med ctf 共享 抽象 fin 進程的地址空間 源碼 instance 該文章是一個系列文章,是本人在Android開發的漫漫長途上的一點感想和記錄,我會盡量按照先易後難的順序進行編寫該系列。該系列引用了《Android開發藝術探索》以及《深入理解Android

Android開發漫漫長途 X——Android序列化

view 編寫 person android中 做了 知識 序列化對象 數據庫 讀者 該文章是一個系列文章,是本人在Android開發的漫漫長途上的一點感想和記錄,我會盡量按照先易後難的順序進行編寫該系列。該系列引用了《Android開發藝術探索》以及《深入理解Androi

Android開發深入理解泛型extends和super的區別

我想 lis dataset 文檔 cnblogs extend 擦除 選擇 提前 摘要: 什麽是泛型?什麽是擦除邊界?什麽是上界限定或下界限定(子類型限定或超類型限定)?什麽是類型安全?泛型extends關和super關鍵字結合通配符?使用的區別,兩種泛型在實際Andro