domingo, 1 de julio de 2012

Notificaciones y Notificicaciones Builder

En nuestras aplicaciones nos puede interesar comunicar cierta información y asegurarnos que el usuario sepa que se ha producido ese evento. Para ello podemos usar el sistema de  notificaciones que Android nos ofrece. Existen dos tipos de notificación: des de un servidor externo (C2DM) o bien des de la propia aplicación. En este post, vamos a hablar de como una aplicación misma puede generar sus propias notificaciones. Veremos que se usa la librería de compatibilidad v4. Este hecho se produce debido a que la clase "Notification" de Android está "deprecated".  A continuación el código:

Antes de empezar
Añadimos la librería de compatibilidad v4.
1.- Crear la carpeta /libs en el proyecto.
2.- Copiar el .jar (de la compatibilidad v4).
3.- Click derecho + add to build path

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gydapp.appNotification"
    android:installLocation="preferExternal"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".NotificationsActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

NotificationsActivity
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.Button;

public class NotificationsActivity extends Activity {

    private final int NOTIFICATION_ID = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // setup notification button
        Button notificationButton = (Button) findViewById(R.id.button);
        notificationButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                createNotification();
            }
        });
    }

    private void createNotification() {

        // setup notifications system
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(this,
                NotificationsActivity.class);
      
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
      
        // Using library compat
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this);
        builder.setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis())
                .setTicker("Notification ticker")
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Notification title")
                .setContentText("Notification text")
                .setAutoCancel(true);
      
        notificationManager.notify(NOTIFICATION_ID, builder.getNotification());
      
           //Notification class the same that Builder
//         Notification notification = new Notification(R.drawable.ic_launcher,
//                "Notification ticker", System.currentTimeMillis());
//
//       
//         notification.flags |= Notification.FLAG_AUTO_CANCEL;
//       
//        notification.setLatestEventInfo(this, "Notification title",
//                "Notification text", pendingIntent);
//        
//        notificationManager.notify(NOTIFICATION_ID, notification);
   
    }
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Generate Notification" >
    </Button>
</RelativeLayout>

A continuación la imagen de la ejecución:



It works!

Roger Sala,

No hay comentarios:

Publicar un comentario