Notification基本通知的兩種寫法

private void newNotify() {
        // 1.創建通知的Builder對象
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this);

        //2.設置參數   對象鏈式操作
        mBuilder.setSmallIcon(R.drawable.ic_launcher); //設置小圖標
        mBuilder.setContentTitle("hello title"); //設置標題
        mBuilder.setContentText("Hello content");//設置內容

        //3.創建一個意圖對象
        Intent resultIntent = new Intent(this, OtherActivity.class);

        //4.創建TaskStackBuilder對象
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        //5.添加到stackBuilder對象中
        stackBuilder.addParentStack(OtherActivity.class);

        //6.添加到頂端
        stackBuilder.addNextIntent(resultIntent);


        //7.意圖對象
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        //8.設置意圖對象
        mBuilder.setContentIntent(resultPendingIntent);

        // 9.獲取NotificationManager對象
       NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        //10.發送通知
       mNotificationManager.notify(mId, mBuilder.build());
    }


    private void oldNotify() {
        // 1.獲取NotificationManager對象
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 2.定義通知
        Notification notification = new Notification();
        // 3.設置參數
        notification.icon = R.drawable.ic_launcher; // 設置圖標
        notification.when = System.currentTimeMillis(); // 發送通知的時間
        // 定義意圖
        Intent intent = new Intent(this, OtherActivity.class);
        // 意圖 :跨進程的意圖
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        // 設置通知的最新事件消息
        notification.setLatestEventInfo(this, "hello title", "hello content",
                pendingIntent);
        // 3.發通知
        manager.notify(1, notification);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章