lunes, 14 de septiembre de 2015

Notification Listener

En esta entrada voy a explicar como hacer un listener para las notificaciones que nos lleguen al dispositivo Android y como leer los datos que contiene. La explicación solo pretende ser un ejemplo práctico, no contiene nada de teoría.


En primer lugar, vamos a crear la clase NotidicationService que extenderá de la classe abstracta NotificationListenerService, ello nos obligará a sobreescribir tres métodos. Nos centraremos en OnCreate() y onNotidicationPosted(), el primero no tiene misterio así que paso por encima sin explicación. En el segundo caso, el método onNotidicationPosted se activa cuando aparece la notificación en la barra de estado, es en ese momento cuando aprovecharemos el objeto StatusBarNotification para extraer los datos que queremos como el titulo o el texto.

Luego montamos un objeto Intent que contendrá toda esa información para que pueda ser utilizada por cualquier otra activity

>Una vez hecho esto, en nuestra Activity principal implementaremos las acciones a realizar cuando salte el evento (El resultado final lo mostramos en un Toast al usuario por comodidad, se puede hacer lo que se tenga en mente con él) y en el manifiesto de android daremos los permisos que se muestran. Otra cosa importante, hay que permitir a nuestra aplicación poder leer las notificaciones, para eso, una vez instalada la aplicación en el dispositivo iremos a configuración --> Sonido y notificaciones --> Acceso a las notificacions --> Activar el check de nuestra aplicación

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 = sbn.getNotification().tickerText.toString();
        Bundle extras = sbn.getNotification().extras;
        String title = extras.getString("android.title");
        String text = extras.getCharSequence("android.text").toString();

        Intent msgrcv = new Intent("Msg");
        msgrcv.putExtra("package", pack);
        msgrcv.putExtra("ticker", ticker);
        msgrcv.putExtra("title", title);
        msgrcv.putExtra("text", text);

        LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);


    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        

    }
}






public class MainActivity extends ActionBarActivity {


    private Handler handler;
    String title;
    String text;
    String ticker;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
        setContentView(R.layout.activity_main);
        
        LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
        
    }



    private BroadcastReceiver onNotice= new BroadcastReceiver() {

        @Override        public void onReceive(Context context, Intent intent) {
            String pack = intent.getStringExtra("package");
            title = intent.getStringExtra("title");
            text = intent.getStringExtra("text");
            ticker = intent.getStringExtra("ticker");

            showToast();

        }
    };

    public void showToast(){
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(), title + " - " + text, Toast.LENGTH_LONG).show();
            }
        });

    }



<service android:name="nextret.com.tstnotification.NotificationService"    android:label="@string/app_name"    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">

    <intent-filter>

        <action android:name="android.service.notification.NotificationListenerService" />

    </intent-filter>

</service>