Question

J'ai un service en cours d'exécution et j'aimerais envoyer une notification. Dommage, l'objet de notification nécessite un contexte , similaire à une activité , et non un service .

Savez-vous un moyen de contourner cela? J'ai essayé de créer une Activité pour chaque notification, mais elle semble laide et je ne trouve pas le moyen de lancer une Activité sans aucune Vue . .

Était-ce utile?

La solution

Activité et Service réellement étend Contexte afin que vous puissiez simplement utiliser this en tant que votre Contexte dans votre 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);

Autres conseils

Ce type de notification est obsolète tel qu'il apparaît dans les documents:

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

Meilleure manière
Vous pouvez envoyer une notification comme celle-ci:

// 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 " + "test@gmail.com")
        .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); 

Meilleure façon
Le code ci-dessus requiert le niveau minimum d’API 11 (Android 3.0).
Si votre niveau d'API minimum est inférieur à 11, vous devez utiliser la classe NotificationCompat de la bibliothèque de support . comme ça.

Ainsi, si le niveau minimum de votre API cible est 4+ (Android 1.6+), utilisez ceci:

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

Eh bien, je ne suis pas sûr si ma solution est la meilleure pratique. En utilisant NotificationBuilder , mon code a l'aspect suivant:

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

Manifeste:

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

et ici le service:

    <service
        android:name=".services.ProtectionService"
        android:launchMode="singleTask">
    </service>

Je ne sais pas s'il existe vraiment un singleTask dans Service , mais cela fonctionne correctement sur mon application ...

Si rien ne fonctionne, essayez getBaseContext () au lieu de contexte ou this .

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top