使用通知侦听器捕获堆叠的通知

时间:2017-02-02 03:29:50

标签: android notifications notification-listener

此问题之前已被问过,但我找不到合适的解决方案。 我尝试使用NotificationListener Service读取通知。这是代码

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();

1 个答案:

答案 0 :(得分:1)

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

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();