使用 Notification Listener 捕获堆叠的通知

Capturing stacked Notifications using Notification Listener

以前有人问过这个问题,但我找不到有效的解决方案。 我正在尝试使用 NotificationListener 服务读取通知。这是代码

import android.app.Notification;  
import android.content.Context;  
import android.content.Intent;  
import android.graphics.Bitmap;  
import android.os.Bundle;  
import android.service.notification.NotificationListenerService;  
import android.service.notification.StatusBarNotification;  
import android.util.Log;  
import android.support.v4.content.LocalBroadcastManager;  

import java.io.ByteArrayOutputStream;  

public class NotificationService extends NotificationListenerService {  

    Context context;  

    @Override  

    public void onCreate() {  

        super.onCreate();  
        context = getApplicationContext();  

    }  
    @Override  

    public void onNotificationPosted(StatusBarNotification sbn) {  
        String pack = sbn.getPackageName();  
        String ticker ="";  
        if(sbn.getNotification().tickerText !=null) {  
            ticker = sbn.getNotification().tickerText.toString();  
        }  
        Bundle extras = sbn.getNotification().extras;  
        String title = extras.getString("android.title");  
        String text = extras.getCharSequence("android.text").toString();  
        int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON);  
        Bitmap id = sbn.getNotification().largeIcon;  


        Log.i("Package",pack);  
        Log.i("Ticker",ticker);  
        Log.i("Title",title);  
        Log.i("Text",text);  

        Intent msgrcv = new Intent("Msg");  
        msgrcv.putExtra("package", pack);  
        msgrcv.putExtra("ticker", ticker);  
        msgrcv.putExtra("title", title);  
        msgrcv.putExtra("text", text);  
        if(id != null) {  
            ByteArrayOutputStream stream = new ByteArrayOutputStream();  
            id.compress(Bitmap.CompressFormat.PNG, 100, stream);  
            byte[] byteArray = stream.toByteArray();  
            msgrcv.putExtra("icon",byteArray);  
        }  
        LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);  


    }  

    @Override  

    public void onNotificationRemoved(StatusBarNotification sbn) {  
        Log.i("Msg","Notification Removed");  

    }  
} 

这很好用,但是当通知堆积起来时,它不会捕获完整的通知。

John:Hi
John:2 new messages

我试过使用以下方法,但那也不起作用。

sbn.getNotification().extras.getCharSequence(Notification.EXTRA_TEXT).toString();

以下方法尝试获取额外的文本行,如果有 none 它会尝试回退到可用的额外大文本。

CharSequence[] lines = 
extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES);
if(lines != null && lines.length > 0) {
   StringBuilder sb = new StringBuilder();
   for (CharSequence msg : lines)
      if (!TextUtils.isEmpty(msg)) {
         sb.append(msg.toString());
         sb.append('\n');
      }
   return sb.toString().trim();
}
CharSequence chars = 
extras.getCharSequence(Notification.EXTRA_BIG_TEXT);
if(!TextUtils.isEmpty(chars))
   return chars.toString();