2017-02-02 17 views
1

この質問は以前に聞かれましたが、解決策が見つかりませんでした。 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(); 

答えて

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(); 
関連する問題