Notification的滑動清除和點擊刪除事件

項目裏面引用了友盟的推送統計,需要統計消息的打開數量和忽略數量

Notification的屬性介紹

audioStreamType 當聲音響起時,所用的音頻流的類型
contentIntent 當通知條目被點擊,就執行這個被設置的Intent
contentView 當通知被顯示在狀態條上的時候,同時這個被設置的視圖被顯示
defaults 指定哪個值要被設置成默認的
deleteIntent 當用戶點擊”Clear All Notifications”按鈕區刪除所有的通知的時候,這個被設置的Intent被執行
icon 狀態條所用的圖片
iconLevel 假如狀態條的圖片有幾個級別,就設置這裏
ledARGB LED燈的顏色
ledOffMS LED關閉時的閃光時間(以毫秒計算)
ledOnMS LED開始時的閃光時間(以毫秒計算)
number 這個通知代表事件的號碼
sound 通知的聲音
tickerText 通知被顯示在狀態條時,所顯示的信息
vibrate 振動模式
when 通知的時間戳

上面我加粗的字體就是正常點擊傳進去的PendingIntent和刪除消息回調的PendingIntent

接收滑動清除和點擊清除事件的回調

  • 先註冊一個廣播接收者
public class NotificationBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        int type = intent.getIntExtra("type", -1);

        if (type != -1) {
            NotificationManager notificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.cancel(type);
        }

        if (action.equals("notification_cancelled")) {
            //處理滑動清除和點擊刪除事件

        }

    }
}
  • 在manifest裏面配置
        <receiver android:name="NotificationBroadcastReceiver所在的路徑">
            <intent-filter>
                <action android:name="notification_cancelled" />
            </intent-filter>

        </receiver>
  • 顯示通知的代碼
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setAutoCancel(true);

        //正常通知點擊會跳轉到MainActivity intent攜帶的參數可以自己獲取
        Intent intentClick = new Intent(this, MainActivity.class);
        intentClick.putExtra("title", "通知標題");
        intentClick.putExtra("message", "通知內容。。。。。。");
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(this, 0,
                intentClick, PendingIntent.FLAG_ONE_SHOT);

        //滑動清除和點擊刪除事件
        Intent intentCancel = new Intent(this,NotificationBroadcastReceiver.class);
        intentCancel.setAction("notification_cancelled");
        intentCancel.putExtra("type", 3);
        intentCancel.putExtra("message","message");
        PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(this,0,
                intentCancel,PendingIntent.FLAG_ONE_SHOT);


        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("message title")
                .setContentText("message content")
                .setContentIntent(pendingIntentClick)//正常點擊
                .setDeleteIntent(pendingIntentCancel);//取消消息回調

        mNotificationManager.notify(103, notificationBuilder.build());
setContentIntent(pendingIntentClick)//正常點擊
setDeleteIntent(pendingIntentCancel);//取消消息回調
這兩個就是設置正常打開消息的設置方法

參考

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