sag*_*gar 8 notifications android
我正在开发的项目有两个不同的应用程序,一个是服务器,另一个是客户端.服务器应用程序有1个服务类,它在onStartCommand()函数中启动服务器线程.服务器线程的类在服务类本身中定义.每当服务器从客户端接收任何数据时,它就存储在数据库中.所以问题是,我想通知用户通过通知或吐司消息到达新数据,尽可能.还告诉我应该在哪里编写通知代码,是否应该在服务类或线程类或firstActivity类中编写我从哪个服务器启动服务器.谢谢.
首先,您需要阅读有关如何使用通知的文章.
接下来使用它来发送通知,您可以在从客户端接收一些数据的位置在服务类中编写此代码.
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);
Run Code Online (Sandbox Code Playgroud)
我读错了吗?您的服务器应用程序和客户端应用程序都在同一台 Android 设备上吗?
无论如何,请查看 ApiDemos,了解通过服务发送通知的代码。
由于您可能要处理远程服务器(而不是本地服务器)以及与网络相关的所有延迟问题,因此我认为您最好将服务包装在 AsyncTask 中。
还要了解广播接收器,注册的广播接收器是触发服务/活动的好方法,而无需无限期循环中拥有自己的服务轮询。
| 归档时间: |
|
| 查看次数: |
28320 次 |
| 最近记录: |