我有一个服务正在运行,我想发送一个通知。太糟糕了,通知对象需要像Activity
这样的Context
,而不是Service
。
你知道有什么方法可以绕过它吗?我试图为每个通知创建一个Activity
,但它看起来很难看,而且我找不到一种没有任何View
的方法来启动Activity
。
发布于 2009-07-30 18:43:44
Activity
和Service
实际上都是extend
Context
,因此您可以简单地使用this
作为Service
中的Context
。
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);
发布于 2015-09-28 10:38:48
@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);
}
发布于 2014-10-02 15:38:14
好吧,我不确定我的解决方案是否是最佳实践。使用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>
我不知道Service
上是否真的有singleTask
,但这在我的应用程序中工作正常……
https://stackoverflow.com/questions/1207269
复制相似问题