xamarin學習筆記A12(安卓Notification)

(每次學習一點xamarin就做個學習筆記和視頻來加深記憶鞏固知識)
如有不正確的地方,請幫我指正。
通知(Notification)簡介
當一個應用程序不在前臺運行而在後臺運行時,這時有個消息希望讓用戶知道,那麼可以在狀態欄顯示一個消息圖標,下拉狀態欄後可以看到具體消息,這就是通知功能。在Activity中一般用得少,主要是用在Service裏。

通知的使用
使用方法很簡單 ,創建一個Notification對象,然後使用NotificationManager對象的Notify方法發送出去。

public class MainActivity : AppCompatActivity,IOnClickListener
    {
        public void OnClick(View v)
        {
            switch (v.Id)
            {
                case Resource.Id.button1://發送通知
                    SendNotice();
                    break;
            }
        }

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView (Resource.Layout.Main);

            Button btn1 = this.FindViewById<Button>(Resource.Id.button1);
            btn1.SetOnClickListener(this);
        }

        private void SendNotice()
        {
            NotificationManager manager = (NotificationManager)this.GetSystemService(NotificationService);
            Notification notification = new NotificationCompat.Builder(this).SetContentTitle("快遞通知")
                .SetContentText("你購買的C#高級編程已發貨了!")
                .SetSmallIcon(Resource.Drawable.a1_16)  //設置顯示在狀態欄的小圖標
                .SetLargeIcon(BitmapFactory.DecodeResource(this.Resources, Resource.Drawable.a1_32))//設置下拉後大圖標
                .SetContentIntent(GetPendingIntent())  //設置點擊通知後要進入的activity
                //.SetAutoCancel(true)  //設置點通知後不再顯示通知
                //SetVibrate振動要在manifest文件中聲明權限"android.permission.VIBRATE",參數500表示有通知來時先等待0.5秒,後面的表示振動1秒停2秒後再振動1秒
                .SetVibrate(new long[] { 500, 1000, 2000, 1000 }) //設置通知來時的振動
                //.SetSound(Android.Net.Uri.FromFile("/system/.........填寫鈴聲具體路徑"))
                .SetLights(Color.Green, 1000, 1000) //第一個時間表示燈閃的時間爲1秒,第二時間表示燈慢慢變暗的時間爲1秒
                .SetPriority(NotificationCompat.PriorityMax) //設置通知優先級
                .Build();
            manager.Notify(12345, notification);
        }

        //點擊通知後要進入的activity
        private PendingIntent GetPendingIntent()
        {
            Intent intent = new Intent(this, typeof(SecondActivity));
            PendingIntent pi = PendingIntent.GetActivity(this, 0, intent, 0);
            return pi;
        }
    }

代碼和視頻在我上傳的CSDN資源中http://download.csdn.net/download/junshangshui/10022512

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