2009-07-30 6 views
82

Ich habe einen Dienst ausgeführt und möchte eine Benachrichtigung senden. Schade, das Benachrichtigungsobjekt benötigt eine Context, wie eine Activity, und keine Service.Senden einer Benachrichtigung von einem Dienst in Android

Kennen Sie einen Weg, um das zu umgehen? Ich habe versucht, eine Activity für jede Benachrichtigung zu erstellen, aber es scheint hässlich, und ich kann keinen Weg finden, eine Activity ohne View zu starten.

+12

Umm ... ein Service _ist_ ein Kontext! –

+13

Gott, ich bin so ein Dummkopf. Ok, tut mir leid, die Zeit zu verschwenden. –

+22

Das ist in Ordnung - es ist eine gute Google-Frage. –

Antwort

91

Sowohl Activity und Service tatsächlich extendContext so können Sie einfach this als Context in Ihrem Service verwenden.

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

Denken Sie daran, dass Sie viele Probleme haben werden, Benachrichtigungen von einem Dienst zu erhalten. Wenn Sie Probleme haben, werfen Sie einen Blick auf diese http://groups.google.com/group/android-developers/browse_thread/thread/e95740e776982f89 – Karussell

+8

Es wäre nett, dies auf die Notification.Builder apis –

+1

zu aktualisieren, wie können Sie Tun Sie dies mit dem Notification.Builder? da setLatestEventInfo bereits veraltet ist. –

67

Diese Art der Mitteilung ist veraltet, wie aus den Dokumenten gesehen:

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

bessere Weg
Sie eine Benachrichtigung wie folgt senden:

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

Der beste Weg
Der obige Code benötigt mindestens API Level 11 (Android 3.0).
Wenn Ihre minimale API-Stufe niedriger als 11 ist, sollten Sie die NotificationCompat-Klasse support library wie folgt verwenden.

Also, wenn Ihr Mindestziel API-Ebene ist 4+ (Android 1.6+) verwenden:

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

Dies sollte die beste Antwort sein, da die akzeptierte ist veraltet –

+3

@MarcelKrivek Scheint er oder sie "vergessen", ihre Quelle zu zitieren. http://www.vogella.com/tutorials/AndroidNotifications/article.html – StarWind0

+0

Was ist "NotificationReceiver"? – user3690202

1

Nun, ich bin nicht sicher, ob meine Lösung Best Practice ist. die NotificationBuilder mein Code sieht wie folgt aus:

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

Manifest:

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

und hier der Service:

Ich weiß nicht, ob es wirklich ein singleTask bei Service ist aber das funktioniert richtig bei meiner anwendung ...

+0

Was ist der Erbauer in diesem? –

+0

Es ist die 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

Es funktioniert einfach. Vielen Dank! –

-2

Wenn nichts davon funktioniert, versuchen Sie getBaseContext() statt context oder this.

+0

Sie sollten 'getBaseContext()' nicht in diesen Szenarien verwenden. –

Verwandte Themen