Android開發之使用Notification.Builder,androidnotification
通知的主要功能是提示功能。例如:簡訊、推送資訊等等。
大體使用步驟:
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 = "未點擊";@Overridepublic 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:// 使用普通的NotificationNotification.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之前不支援ButtonMyNotification();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() {@Overridepublic 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以後才能使用,BigTextStyleNotification.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以後才能使用,InboxStyleNotification.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;}}@Overrideprotected 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() {@Overridepublic 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。