2009-07-30 17 views
82

Tengo un servicio en ejecución y me gustaría enviar una notificación. Lástima, el objeto de notificación requiere un Context, como un Activity, y no un Service.Enviar una notificación desde un servicio en Android

¿Conoces alguna forma de pasar eso? Traté de crear un Activity para cada notificación, pero parece feo, y no puedo encontrar una manera de ejecutar un Activity sin ningún View.

+12

Umm ... a Service _is_ a context! –

+13

Dios, yo soy tan tonto. Bien, perdón por perder el tiempo de todos. –

+22

Está bien, es una buena pregunta de Google. –

Respuesta

91

Tanto Activity y Service realidad extendContext por lo que puede simplemente usar this como su Context dentro de su Service.

NotificationManager notificationManager = 
    (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE); 
Notification notification = new Notification(/* your notification */); 
PendingIntent pendingIntent = /* your intent */; 
notification.setLatestEventInfo(this, /* your content */, pendingIntent); 
notificationManager.notify(/* id */, notification); 
+3

Tenga en cuenta que tendrá muchos problemas para notificar a un servicio. Si tiene problemas, eche un vistazo a este http://groups.google.com/group/android-developers/browse_thread/thread/e95740e776982f89 – Karussell

+8

Sería bueno actualizar esto a Notification.Builder apis –

+1

cómo puede hacer esto usando el Notification.Builder? porque setLatestEventInfo ya está en desuso. –

67

este tipo de notificación es obsoleto como se ve a partir de documentos:

@java.lang.Deprecated 
public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ } 

public Notification(android.os.Parcel parcel) { /* compiled code */ } 

@java.lang.Deprecated 
public void setLatestEventInfo(android.content.Context context, java.lang.CharSequence contentTitle, java.lang.CharSequence contentText, android.app.PendingIntent contentIntent) { /* compiled code */ } 

mejor manera
Puede enviar una notificación de esta manera:

// prepare intent which is triggered if the 
// notification is selected 

Intent intent = new Intent(this, NotificationReceiver.class); 
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0); 

// build notification 
// the addAction re-use the same intent to keep the example short 
Notification n = new Notification.Builder(this) 
     .setContentTitle("New mail from " + "[email protected]") 
     .setContentText("Subject") 
     .setSmallIcon(R.drawable.icon) 
     .setContentIntent(pIntent) 
     .setAutoCancel(true) 
     .addAction(R.drawable.icon, "Call", pIntent) 
     .addAction(R.drawable.icon, "More", pIntent) 
     .addAction(R.drawable.icon, "And more", pIntent).build(); 


NotificationManager notificationManager = 
    (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

notificationManager.notify(0, n); 

mejor manera
El código anterior necesita un nivel mínimo de API 11 (Android 3.0).
Si su nivel mínimo de API es menor que 11, debe usar la clase NotificationCompat de support library de esta manera.

Así que si su nivel mínimo API objetivo 4+ (Android 1.6+) usar esto:

import android.support.v4.app.NotificationCompat; 
    ------------- 
    NotificationCompat.Builder builder = 
      new NotificationCompat.Builder(this) 
        .setSmallIcon(R.drawable.mylogo) 
        .setContentTitle("My Notification Title") 
        .setContentText("Something interesting happened"); 
    int NOTIFICATION_ID = 12345; 

    Intent targetIntent = new Intent(this, MyFavoriteActivity.class); 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
    builder.setContentIntent(contentIntent); 
    NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    nManager.notify(NOTIFICATION_ID, builder.build()); 
+4

esta debería ser la mejor respuesta ya que la aceptada está obsoleta –

+3

@MarcelKrivek Parece que él o ella "olvidó" citar su fuente. http://www.vogella.com/tutorials/AndroidNotifications/article.html – StarWind0

+0

¿Qué es "NotificationReceiver"? – user3690202

1

Bueno, no estoy seguro de si mi solución es la mejor práctica. Utilizando el NotificationBuilder mi código es el que:

private void showNotification() { 
    Intent notificationIntent = new Intent(this, MainActivity.class); 

    PendingIntent contentIntent = PendingIntent.getActivity(
       this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
    builder.setContentIntent(contentIntent); 
    NotificationManager notificationManager = 
      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    notificationManager.notify(NOTIFICATION_ID, builder.build()); 
    } 

Manifiesto:

<activity 
     android:name=".MainActivity" 
     android:launchMode="singleInstance" 
    </activity> 

y aquí el servicio:

no sé si realmente hay un singleTask en Service pero esto funciona correctamente en mi aplicación ...

+0

¿cuál es el constructor en esto? –

+0

Es el NotificationCompat.Builder ... –

7
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
public void PushNotification() 
{ 
    NotificationManager nm = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); 
    Notification.Builder builder = new Notification.Builder(context); 
    Intent notificationIntent = new Intent(context, MainActivity.class); 
    PendingIntent contentIntent = PendingIntent.getActivity(context,0,notificationIntent,0); 

    //set 
    builder.setContentIntent(contentIntent); 
    builder.setSmallIcon(R.drawable.cal_icon); 
    builder.setContentText("Contents"); 
    builder.setContentTitle("title"); 
    builder.setAutoCancel(true); 
    builder.setDefaults(Notification.DEFAULT_ALL); 

    Notification notification = builder.build(); 
    nm.notify((int)System.currentTimeMillis(),notification); 
} 
+0

Simplemente funciona. ¡Gracias! –

-2

Si ninguno de estos funciona, intente getBaseContext(), en lugar de context o this.

+0

No debe usar 'getBaseContext()' estos escenarios. –

Cuestiones relacionadas