Xamarin.Android 裏面的通知

我們每天都離不開手機App應用,也每天都接受各種消息通知,這幾天自己剛好在研究Xamarin.Android 裏面的通知,在此做個筆記總結,有什麼理解不當之處請大家指正。

(1)首先在界面拖3個Button

(2)在MainActivity裏面找到界面的對應Button元素(我設定三個Button的ID分別爲(button1,button2,button3)

  Button StartButton = FindViewById<Button>(Resource.Id.button1);
            Button EndButton = FindViewById<Button>(Resource.Id.button2);
            Button VoiceButton = FindViewById<Button>(Resource.Id.button3);

(3)定義一個NotificationManager類型的變量,我取名爲notification

 private NotificationManager notification;

(4)獲取管理通知類,在Xamarin.Android下的通知需要獲取NotificationManager服務,而該服務需要通過GetSystemService獲取

 <span style="font-size:18px;">//獲得系統管理類</span>
            notification = (NotificationManager) GetSystemService(NotificationService);

(5)爲三個button分別掛載事件

   //開始通知
            StartButton.Click += delegate
            {
                //設置通知的圖標以及顯示的簡介Title
                Notification notify = new Notification(Resource.Drawable.Icon, "普通通知");
                //初始化點擊通知後打開的活動,我們點擊通知之後都會打開對應的活動,所以我們需要初始化一個延遲意圖,以便通知可以打開
                PendingIntent pintent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(MainActivity)), PendingIntentFlags.UpdateCurrent);
                //設置通知的主體
                notify.SetLatestEventInfo(this, "通知李白", "你二級沒過", pintent);
                //發送通知
                notification.Notify(0, notify);//0爲該通知的ID,方便後面接收該通知
            };
在取消通知裏面,notification裏面的Cancel方法裏面的參數是通知ID,是根據ID來區分究竟應該取消哪一個通知,或者你也可以選擇All,進而選擇取消全部通知
  //取消通知
            EndButton.Click += delegate
            {
                //根據ID取消通知
                notification.Cancel(0);
                notification.Cancel(1);
            };
  //帶有震動,聲音的通知
            VoiceButton.Click += delegate
            {
                Notification notify = new Notification(Resource.Drawable.Icon, "帶有聲音、LED光和震動的通知");
                //設置該通知具有聲音、LED光和震動,即所有
                notify.Defaults = NotificationDefaults.All;

                //獲取系統默認的通知聲音
                Android.Net.Uri ringUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
                //設置通知的聲音
                notify.Sound = ringUri;

                //設置一秒的震動
                notify.Vibrate = new long[] { 1000 };
                //設置LED的顏色爲綠色
                notify.LedARGB = Color.Green;
                //設置LED顯示時間爲1s
                notify.LedOnMS = 1000;
                //設置LED熄滅時間爲1s
                notify.LedOffMS = 1000;
                //設置標誌位,否則無法顯示LED
                notify.Flags = NotificationFlags.ShowLights | notify.Flags;

                PendingIntent pintent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(MainActivity)), 0);

                notify.SetLatestEventInfo(this, "通知璐璐", "回來喫餃子", pintent);

                notification.Notify(1, notify);

            };
最後打開Genymotion模擬器,運行一下



好了,大功告成!繼續,革命尚未成功,“通知”仍需努力。


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