Notification 學習

第一行代碼中的 第8章 運用手機多媒體中的通知方法已經過時,今天來記錄一下notice的學習
這裏寫圖片描述
書中的4個步驟已被替代,在得到通知管理器後,創建Notification對象後在裏面設置相應的內容(Notification.Builder),包括通知標題、內容、時間、圖標等信息,下面就上碼
MainActivity.class

package com.superxingyun.notificationtest;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

        sendNotice = (Button) findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        String text = "This is content text";
        switch (view.getId()) {
            case R.id.send_notice:
                //通知管理
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                Notification notification = new Notification.Builder(this).setContentTitle("New Notice")
                .setContentText(text).setSmallIcon(R.mipmap.ic_launcher).build();//通知內容設置
                Intent intent = new Intent(this, NotificationActivity.class);//通知點擊事件跳轉到另一個活動
                PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
                notification.contentIntent = pi;
                notification.defaults = Notification.DEFAULT_ALL;//設置通知默認效果
                manager.notify(1, notification);
                break;
            default:
                break;
        }
    }
}

主要內容都這這裏,AndroidManifest中記得添加

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

這個權限,以及註冊點擊通知後跳轉的活動,最後在新的活動所對應的java文件中將通知欄的通知取消:

//點擊通知後清楚狀態欄通知
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(1);

manger.cancel穿進去的參數就是之前設置通知的id

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