2009-07-30 12 views
82

Ho un servizio in esecuzione e desidero inviare una notifica. Peccato, l'oggetto di notifica richiede un Context, come un Activity, e non uno Service.Invio di una notifica da un servizio in Android

Conosci qualche modo per farlo? Ho provato a creare un Activity per ogni notifica, ma sembra brutto, e non riesco a trovare un modo per avviare un Activity senza alcun View.

+12

Umm ... un servizio _is_ un contesto! –

+13

Dio, sono un tale manubrio. Ok, mi dispiace sprecare il tempo di tutti. –

+22

Va bene - è una buona domanda su Google. –

risposta

91

Sia Activity e Service realtà extendContext così si può semplicemente utilizzare this come Context all'interno 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

Ricorda che avrai molti problemi nella notifica da un servizio. Se hai problemi, dai un'occhiata a questo http://groups.google.com/group/android-developers/browse_thread/thread/e95740e776982f89 – Karussell

+8

Sarebbe bello aggiornarlo al Notification.Builder apis –

+1

come puoi fai questo usando Notification.Builder? perché setLatestEventInfo è già deprecato. –

67

questo tipo di notifica è deprecato come si è visto da documenti:

@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 */ } 

Modo migliore
È possibile inviare una notifica come questo:

// 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); 

Il modo migliore
Il codice sopra richiede un livello API minimo 11 (Android 3.0).
Se il tuo livello API minimo è inferiore a 11, dovresti usare la classe NotificationCompat di support library come questa.

Così, se il livello di obiettivo minimo API è 4+ (Android 1.6+) utilizzare questo:

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

questa dovrebbe essere la migliore risposta dato che quella accettata è deprecata –

+3

@MarcelKrivek Sembra che abbia "dimenticato" di citare la fonte. http://www.vogella.com/tutorials/AndroidNotifications/article.html – StarWind0

+0

Che cos'è "NotificationReceiver"? – user3690202

1

Beh, io non sono sicuro se la mia soluzione è delle migliori pratiche. Utilizzando il NotificationBuilder il mio codice è simile che:

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()); 
    } 

manifesto:

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

e qui il servizio:

non so se c'è davvero un singleTask a Service ma questo funziona correttamente nella mia applicazione ...

+0

qual è il costruttore in questo? –

+0

È il 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

Funziona. Grazie! –

-2

Se nessuno di questi funziona, provare getBaseContext(), anziché context o this.

+0

Non si dovrebbe usare 'getBaseContext()' sono questi scenari. –

Problemi correlati