【问题标题】:How to show notification from background service?如何显示来自后台服务的通知?
【发布时间】:2018-03-20 14:20:48
【问题描述】:

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

【问题讨论】:

标签: android notifications


【解决方案1】:

首先你需要阅读这篇关于如何使用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);

【讨论】:

    【解决方案2】:

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

    无论如何,请查看 ApiDemos 以获取通过服务进行通知的代码。

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

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

    【讨论】:

    • 谢谢!我的服务器和客户端应用程序在不同的模拟器上运行,数据传输和存储在数据库中没有问题。我将看看广播接收器。有什么方法可以检测数据库表的变化吗?这样,如果发现更改,我可以从活动类通知用户。
    • 正如你所说,我使用了广播接收器,它正在工作,但我想发送 1 个带有广播的字符串并在 toast 消息中显示该字符串。我使用了intent.putextra()。但是在接收端我收到空值,我认为问题在于我获取额外的代码,你能告诉我如何接收广播意图发送的数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2023-01-18
    相关资源
    最近更新 更多