从Android中的服务发送通知


105

我有一个正在运行的服务,并想发送通知。太糟糕了,通知对象需要一个Context,例如和Activity,而不是Service

你知道绕过那条路吗?我尝试Activity为每个通知创建一个,但是它看起来很丑陋,而且我找不到Activity没有任何方法来启动的方法View


14
嗯...服务就是背景!
艾萨克·沃勒

19
天哪,我真笨。好的,很抱歉浪费大家的时间。
e-satis

28
很好-这是一个很好的Google问题。
艾萨克·沃勒

喜欢您的第二条评论:D:D
Faizan Mubasher

此帖刚刚保存了我的一天...
穆罕默德·法赞

Answers:


109

无论ActivityService实际extend Context,所以你可以简单地使用this作为您Context在您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);

4
请记住,从服务进行通知时会遇到很多问题。如果您有问题,请查看此groups.google.com/group/android-developers/browse_thread/thread/…–
Karussell

1
如何使用Notification.Builder做到这一点?因为setLatestEventInfo已被弃用。
Kairi San

77

从文档中可以看出,此通知类型已弃用:

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

更好的方法
您可以发送如下通知:

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


上面的最佳方法代码需要最低API级别11(Android 3.0)。
如果您的最低API级别低于11,则应使用支持库的NotificationCompat类,如下所示。

因此,如果您的最低目标API级别为4+(Android 1.6+),请使用以下代码:

    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
这是最好的答案,因为已弃用了公认的答案
Marcel Krivek 2015年

4
@MarcelKrivek似乎“忘记”引用了他们的消息来源。vogella.com/tutorials/AndroidNotifications/article.html
StarWind0 '16

什么是“ NotificationReceiver”?
user3690202 '17

“ NotificationReceiver”是将由通知打开的活动。检查@ StarWind0提供的链接。
乔治·西奥多拉基斯

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

主题问题来自“服务而非活动”
Duna,

1

好吧,我不确定我的解决方案是否是最佳实践。使用NotificationBuilder我的代码如下所示:

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

表现:

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

这里的服务:

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

我不知道是否真的有singleTaskat,Service但这在我的应用程序中可以正常使用...


这是什么建造者?
Viswanath Lekshmanan

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.