2011-11-25 10 views
11
int icon = R.drawable.icon4;   
CharSequence tickerText = "Hello"; // ticker-text 
long when = System.currentTimeMillis();   
Context context = getApplicationContext();  
CharSequence contentTitle = "Hello"; 
CharSequence contentText = "Hello";  
Intent notificationIntent = new Intent(this, Example.class); 
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
Notification notification = new Notification(icon, tickerText, when); 
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 

Esto no funcionará para mí.¿Cómo crear notificaciones que no desaparecen cuando se hace clic en Android?

¿Cómo puedo crear una notificación que se pueda hacer clic y vaya a mi aplicación, pero que no desaparece cuando se hace clic en ella?

+0

similar: http://stackoverflow.com/questions/6391870/how-exactly-to-use-notification-builder/35279147#35279147 –

Respuesta

25

Debe leer todo el asunto, no solo una parte, amigo. Por favor vuelva a leer cuidadosamente paso a paso.

// this 
String ns = Context.NOTIFICATION_SERVICE; 
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 

int icon = R.drawable.icon4;   
CharSequence tickerText = "Hello"; // ticker-text 
long when = System.currentTimeMillis();   
Context context = getApplicationContext();  
CharSequence contentTitle = "Hello"; 
CharSequence contentText = "Hello";  
Intent notificationIntent = new Intent(this, Example.class); 
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
Notification notification = new Notification(icon, tickerText, when); 
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 

// and this 
private static final int HELLO_ID = 1; 
mNotificationManager.notify(HELLO_ID, notification); 
+6

'setLatestEventInfo()' desfasada en el nivel API 11 . Tiene que usar [Notification.Builder] (http://developer.android.com/reference/android/app/Notification.Builder.html) en su lugar. – AnujAroshA

+0

Tengo el mismo código para la notificación .. Ahora, si quiero agregar el botón en la notificación, ¿cómo puedo lograr ...? Por favor, ayúdenme – ADT

+0

Tengo un problema, configuro el icono de color verde, pero cuando aparece la notificación cambia automáticamente a blanco. –

12
int icon = R.drawable.ic_launcher; 
long when = System.currentTimeMillis(); 
NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
Intent intent=new Intent(context,MainActivity.class); 
PendingIntent pending=PendingIntent.getActivity(context, 0, intent, 0); 
Notification notification; 
    if (Build.VERSION.SDK_INT < 11) { 
     notification = new Notification(icon, "Title", when); 
     notification.setLatestEventInfo(
       context, 
       "Title", 
       "Text", 
       pending); 
    } else { 
     notification = new Notification.Builder(context) 
       .setContentTitle("Title") 
       .setContentText(
         "Text").setSmallIcon(R.drawable.ic_launcher) 
       .setContentIntent(pending).setWhen(when).setAutoCancel(true) 
       .build(); 
    } 
notification.flags |= Notification.FLAG_AUTO_CANCEL; 
notification.defaults |= Notification.DEFAULT_SOUND; 
nm.notify(0, notification); 

o puede descargar directamente de tutorial aquí: http://www.demoadda.com/demo/android/how-to-create-local-notification-notification-manager-demo-with-example-android-source-code_26

+1

¿Es esto correcto? Usted crea un 'PendingIntent' pero no se usa entonces. Al menos cuando <11, debería ser el último parámetro para 'setLatestEventInfo', ¿o estoy equivocado? – hgoebl

+0

@hgoebl: ver mi edición ... – Kishan

+0

Tengo un problema al configurar el icono de color verde, pero cuando aparece la notificación cambia automáticamente a blanco. –

2

Si está utilizando Android 5.0> se hizo mucho más fácil, funcionabilidad cambió, pero se puede utilizar el mismo código.

//Some Vars 
public static final int NOTIFICATION_ID = 1; //this can be any int 


//Building the Notification 
NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
builder.setSmallIcon(R.drawable.ic_stat_notification); 
builder.setContentTitle("BasicNotifications Sample"); 
builder.setContentText("Time to learn about notifications!"); 

NotificationManager notificationManager = (NotificationManager) getSystemService(
      NOTIFICATION_SERVICE); 
notificationManager.notify(NOTIFICATION_ID, builder.build()); 

Asegúrese de que está en un contexto de aplicación, si no es posible que tenga que pasar el contexto y cambiar su código fuente de la siguiente manera

NotificationCompat.Builder builder = new NotificationCompat.Builder(context); 
... 
.. 
. 

NotificationManager notificationManager = (NotificationManager) context.getSystemService(
      context.NOTIFICATION_SERVICE); 

Se puede ver el código fuente completo en-: https://github.com/googlesamples/android-BasicNotifications/blob/master/Application/src/main/java/com/example/android/basicnotifications/MainActivity.java#L73

+0

Tengo un problema para configurar el icono de color verde, pero cuando aparece la notificación cambia a blanco automáticamente. –

0
if (android.os.Build.VERSION.SDK_INT>16) 
    { 
     notificationManager.notify(5, notification.build()); 
    }else 
    { 
     notificationManager.notify(5, notification.getNotification()); 
    } 

trabajar en android.os.Build.VERSION.SDK_INT<16 tener en cuenta que hacer algunos cambios

1

Aquí es código

Intent intent = new Intent(this, MainActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 
       PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.mipmap.ic_launcher) 
       .setContentTitle("Push Notification") 
       .setContentText(messageBody) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager.notify(0, notificationBuilder.build()); 

aquí si desea que las notificaciones que no desaparecen cuando se hace clic en Android? Así que establezca

setAutoCancel(false); 
Cuestiones relacionadas