如何显示后台服务的通知?

时间:2011-10-09 07:02:52

标签: android notifications

我正在开发的项目有两个不同的应用程序,一个是服务器,另一个是客户端。服务器应用程序有1个服务类,它在onStartCommand()函数中启动服务器线程。服务器线程的类在服务类本身中定义。每当服务器从客户端接收任何数据时,它就存储在数据库中。所以问题是,我想通知用户通过通知或吐司消息到达新数据,尽可能。还告诉我应该在哪里编写通知代码,是否应该在服务类或线程类或firstActivity类中编写,我将从中启动服务器服务。谢谢。

2 个答案:

答案 0 :(得分:9)

首先,您需要阅读有关如何使用Notifications的文章。

接下来使用它来发送通知,您可以在从客户端接收一些数据的位置在服务类中编写此代码。

NotificationManager notificationManager =
    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int icon = R.drawable.notification_icon;
CharSequence notiText = "Your notification from the service";
long meow = System.currentTimeMillis();

Notification notification = new Notification(icon, notiText, meow);

Context context = getApplicationContext();
CharSequence contentTitle = "Your notification";
CharSequence contentText = "Some data has arrived!";
Intent notificationIntent = new Intent(this, YourActivityThatYouWantToLaunch.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

int SERVER_DATA_RECEIVED = 1;
notificationManager.notify(SERVER_DATA_RECEIVED, notification);

答案 1 :(得分:3)

我读错了吗?您的服务器应用和客户端应用都在同一个Android设备上?

在任何情况下,请查看ApiDemos以获取服务通知的代码。

由于您可能正在处理远程服务器(而不是本地服务器)以及与网络相关的所有延迟问题,我认为您最好将服务包装在AsyncTask中。

了解广播接收器,注册的广播接收器可以很好地触发服务/活动,而无需在循环中无限期地进行自己的服务轮询。