Uso de notificación bajo diferentes apiLevels

Reimpreso de: http://www.cnblogs.com/Arture/p/5523695.html


Existen algunas diferencias en el uso de Notificación en diferentes versiones, que involucran el uso de Builder. Ahora resumido de la siguiente manera, espero que sea útil para los programadores que lo usarán en el futuro.


 
En sistemas por debajo del nivel de API 11 , es decir, sistemas por debajo de Android 2.3.3, la función setLatestEventInfo () es el único método de implementación. No se mencionarán aquí las configuraciones anteriores de propiedades relacionadas Hay muchos materiales en línea.

 Intent  intent = new Intent(this,MainActivity);  
 PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);  
 notification.setLatestEventInfo(context, title, message, pendingIntent);          
 manager.notify(id, notification); 

En sistemas superiores al nivel de API 11 e inferiores al nivel de API 16 (Android 4.1.2), puede utilizar Notification.Builder para construir funciones. Pero usar getNotification () para hacer que la notificación se dé cuenta. En este punto, las banderas, el icono y otros atributos establecidos en la notificación en la versión anterior no son válidos y deben configurarse en el constructor.

Notification.Builder builder = new Notification.Builder(context)  
            .setAutoCancel(true)  
            .setContentTitle("title")  
            .setContentText("describe")  
            .setContentIntent(pendingIntent)  
            .setSmallIcon(R.drawable.ic_launcher)  
            .setWhen(System.currentTimeMillis())  
            .setOngoing(true);  
notification=builder.getNotification();

Para versiones superiores al nivel de API 16 , puede utilizar las funciones Builder y build () para facilitar el uso de notificaciones.

 Notification notification = new Notification.Builder(context)    
          .setAutoCancel(true)    
          .setContentTitle("title")    
          .setContentText("describe")    
          .setContentIntent(pendingIntent)    
          .setSmallIcon(R.drawable.ic_launcher)    
          .setWhen(System.currentTimeMillis())    
          .build();


【punto importante】:

    Hay muchas formas de escribir notificaciones cuando se crean notificaciones, pero debe tenerse en cuenta que cuando se usa
  Notificación notificación = nueva Notificación ();
  este método de construcción, debe agregar la configuración notificación.icon, de lo contrario, el programa no reportará un error, pero no tendrá ningún efecto. 


Problema:


cuando se utiliza el método setLatestEventInfo () en Notificación , Eclipse indica: "El método setLatestEventInfo (Context, String, String, PendingIntent) no está definido para el tipo Notification".
Motivo: se ha eliminado el método setLatestEventInfo.
/**
* Sets the {@link #contentView} field to be a view with the standard "Latest Event"
* layout.
*
* <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields
* in the view.</p>
* @param context The context for your application / activity.
* @param contentTitle The title that goes in the expanded entry.
* @param contentText The text that goes in the expanded entry.
* @param contentIntent The intent to launch when the user clicks the expanded notification.
* If this is an activity, it must include the
* {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
* that you take care of task management as described in the
* <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
* Stack</a> document.
*
* @deprecated Use {@link Builder} instead.
* @removed
*/
@Deprecated


public void setLatestEventInfo(Context context,
CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
Notification.Builder builder = new Notification.Builder(context);


// First, ensure that key pieces of information that may have been set directly
// are preserved
builder.setWhen(this.when);
builder.setSmallIcon(this.icon);
builder.setPriority(this.priority);
builder.setTicker(this.tickerText);
builder.setNumber(this.number);
builder.setColor(this.color);
builder.mFlags = this.flags;
builder.setSound(this.sound, this.audioStreamType);
builder.setDefaults(this.defaults);
builder.setVibrate(this.vibrate);
builder.setDeleteIntent(this.deleteIntent);


// now apply the latestEventInfo fields
if (contentTitle != null) {
builder.setContentTitle(contentTitle);
}
if (contentText != null) {
builder.setContentText(contentText);
}
builder.setContentIntent(contentIntent);
builder.buildInto(this);
}


Supongo que te gusta

Origin blog.csdn.net/u012049463/article/details/67635150
Recomendado
Clasificación