Notification的發送與取消

我們經常能在生活中收到各種通知,短信就是最明顯的例子。。


關於android的通知我們通過一個小案例來簡單實現以下。。


首先看xml代碼,我放置了兩個按鈕,分別爲取消和發送:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.xiati.notification1.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send notifucation"
        android:id="@+id/send"
        android:layout_marginTop="30dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="cancel notification"
        android:id="@+id/cancel"
        android:layout_alignTop="@+id/send"
        android:layout_toEndOf="@+id/send"/>
</RelativeLayout>

然後看activity的處理:

package com.example.xiati.notification1;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{


    private Button sendBtn;

    private Button cancelBtn;

    private NotificationManager notificationManager;

    public static final int NOTIFICATION_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sendBtn = (Button)findViewById(R.id.send);
        cancelBtn = (Button)findViewById(R.id.cancel);
        // 發送通知點擊事件
        sendBtn.setOnClickListener(this);
        // 取消通知點擊事件
        cancelBtn.setOnClickListener(this);
        // 註冊通知服務
        notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){

            case R.id.send:

                sendNotification();
                break;
            case R.id.cancel:

                notificationManager.cancel(NOTIFICATION_ID);
                break;
        }
    }

    /**
     * 發送通知
     */
    public void sendNotification(){

        Intent intent = new Intent(this, MainActivity.class);

        // 創建一個點擊通知的處理
        PendingIntent pendingIntent = PendingIntent.getActivities(this, 0, new Intent[]{intent} ,0);

        Notification.Builder builder = new Notification.Builder(this);
        // 設置小圖標
        builder.setSmallIcon(R.drawable.xiatianlong);
        // 設置通知時狀態欄顯示的文本
        builder.setTicker("通知狀態欄的顯示文本");
        // 設置通知的時間(此處去系統的當前時間)
        builder.setWhen(System.currentTimeMillis());
        // 設置通知的標題
        builder.setContentTitle("通知標題");
        // 設置通知的內容
        builder.setContentText("通知的內容");
        // 設置點擊跳轉
        builder.setContentIntent(pendingIntent);
        // 設置通知音
        builder.setDefaults(Notification.DEFAULT_SOUND);

        Notification notification = builder.build();

        notificationManager.notify(NOTIFICATION_ID ,notification);
    }
}


下面來談談notification,這個notification一般用在電話,短信,郵件,鬧鐘鈴聲,在手機的狀態欄上就會出現一個小圖標,提示用戶處理這個快訊,這時手從上方滑動狀態欄就可以展開並處理這個快訊。發現這個功能特別好用,所以我就根據我的理解來談談。摘自幫助文檔 :  notification類表示一個持久的通知,將提交給用戶使用NotificationManager。已添加的Notification.Builder,使其更容易構建通知。notification是一種讓你的應用程序在沒有開啓情況下或在後臺運行警示用戶。它是看不見的程序組件(Broadcast Receiver,Service和不活躍的Activity)警示用戶有需要注意的事件發生的最好途徑。

    先來區分以下狀態欄和狀態條的區別:

    1、狀態條就是手機屏幕最上方的一個條形狀的區域;

          在狀態條有好多信息量:比如usb連接圖標,手機信號圖標,電池電量圖標,時間圖標等等;

    2、狀態欄就是手從狀態條滑下來的可以伸縮的view;

          在狀態欄中一般有兩類(使用FLAG_標記):

          (1)正在進行的程序;

          (2)是通知事件;

     大概來描述創建一個Notification傳送的信息有:

    1、一個狀態條圖標;

    2、在拉伸的狀態欄窗口中顯示帶有大標題,小標題,圖標的信息,並且有處理該點擊事件:比如調用該程序的入口類;

    3、閃光,LED,或者震動;

      快速創建一個Notification的步驟簡單可以分爲以下四步:

      第一步:通過getSystemService()方法得到NotificationManager對象;

      第二步:對Notification的一些屬性進行設置比如:內容,圖標,標題,相應notification的動作進行處理等等;

      第三步:通過NotificationManager對象的notify()方法來執行一個notification的快訊;

      第四步:通過NotificationManager對象的cancel()方法來取消一個notificatioin的快訊;

     下面對Notification類中的一些常量,字段,方法簡單介紹一下:

     常量:

        DEFAULT_ALL                  使用所有默認值,比如聲音,震動,閃屏等等

        DEFAULT_LIGHTS            使用默認閃光提示

        DEFAULT_SOUNDS         使用默認提示聲音

        DEFAULT_VIBRATE         使用默認手機震動

      【說明】:加入手機震動,一定要在manifest.xml中加入權限:

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

        以上的效果常量可以疊加,即通過

                mNotifaction.defaults =DEFAULT_SOUND  |  DEFAULT_VIBRATE ; 

            或mNotifaction.defaults |=DEFAULT_SOUND   (最好在真機上測試,震動效果模擬器上沒有)

        //設置flag位

        FLAG_AUTO_CANCEL          該通知能被狀態欄的清除按鈕給清除掉

        FLAG_NO_CLEAR                  該通知能被狀態欄的清除按鈕給清除掉

        FLAG_ONGOING_EVENT      通知放置在正在運行

        FLAG_INSISTENT                    是否一直進行,比如音樂一直播放,知道用戶響應

      常用字段:

           contentIntent                  設置PendingIntent對象,點擊時發送該Intent

           defaults                             添加默認效果

           flags                                  設置flag位,例如FLAG_NO_CLEAR等

           icon                                  設置圖標

           sound                                設置聲音

           tickerText                        顯示在狀態欄中的文字

           when                                發送此通知的時間戳

 

Notification.build構造Notification方法介紹:  

     void setLatestEventInfo(Context context , CharSequencecontentTitle,CharSequence  contentText,PendingIntent contentIntent)  

          

        功能: 顯示在拉伸狀態欄中的Notification屬性,點擊後將發送PendingIntent對象

        參數: context             上下文環境

                   contentTitle      狀態欄中的大標題

                   contentText      狀態欄中的小標題

                   contentIntent    點擊後將發送PendingIntent對象

      說明:要是在Notification中加入圖標,在狀態欄和狀態條中顯示圖標一定要用這個方法,否則報錯!

      最後說一下NotificationManager類的常用方法:

             通過獲取系統服務來獲取該對象:           

                NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE) ;

      NotificationManager常用方法介紹:

               public  void cancelAll()                                                          移除所有通知 (只是針對當前Context下的Notification)

               public  void cancel(int id)                                                      移除標記爲id的通知 (只是針對當前Context下的所有Notification)

               public  void notify(String tag ,int id, Notification notification) 將通知加入狀態欄, 標籤爲tag,標記爲id

               public  void notify(int id, Notification notification)                   將通知加入狀態欄,,標記爲id

首先,我感覺在實現中PendingIntent感覺就是Intent的包裝。

它的三個實例化方法:

getActivity(Context, int, Intent, int)

getService(Context, int, Intent, int)

getBroadcast(Context, int, Intent, int)

感覺是保存當前的Activity的Context,然後在外部啓動Intent動作。類似於代碼Context.startActivity(*, *);

常和Notification和Alarm一起使用。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章