![](/img/trans.png)
[英]How to make a Facebook Messenger-like notification like this in Android
[英]android how to create a service that make a notification in real time (like facebook or whatapps)
我正在尝试创建一个后台服务,每隔“X”分钟查询一次web服务,如果响应“ok”,则在通知栏上生成通知
我不确定是否是一个Android服务o广播接收器我需要的东西
不管怎样,谢谢
NotificationManager似乎是您正在寻找的。
请不要每隔X分钟从网络服务中提取一页 - 这会耗尽电池电量,使用Google云消息传递 (以前的C2DM - 云到设备消息传递)来获取您的信息更新 - 它非常轻巧,非常高效并共享所有应用程序的一个现有数据连接。
首先,你需要一个广播接收器(在它自己的类中,加上清单中的一些代码)对USER_PRESENT动作(当用户解锁屏幕时)或BOOT_COMPLETED(当手机完成加载操作系统和所有其他东西时)做出反应。 Boot激活Broadcast,广播启动服务。 在服务的onStartCommand()方法中,每X分钟运行一次与Web服务的连接。 您的服务应该实现AsyncTask以连接到Web服务。 在该任务的onCompleted()方法中,您可以调用通知。
表现:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name="classes.myReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name="classes.myService">
</service>
类:
public class myReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context ctx, Intent intent) {
Intent service = new Intent(ctx, myService.class);
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)||intent.getAction().equals(Intent.ACTION_USER_PRESENT)||intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
ctx.startService(service);
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
ctx.stopService(service);
}
}
}
样品通知
private void showNotification() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContent(getNotificationContent());
notificationBuilder.setOngoing(true);
notificationBuilder.setTicker("Hello");
notificationBuilder.setSmallIcon(R.drawable.notif_icon);
mNotificationManager.notify(R.id.notification_layout, notificationBuilder.build());
}
private RemoteViews getNotificationContent() {
RemoteViews notificationContent = new RemoteViews(getPackageName(), R.layout.keyphrase_recogniser_notification);
notificationContent.setTextViewText(R.id.notification_title, "title");
notificationContent.setTextViewText(R.id.notification_subtitle, "subtitle");
return notificationContent;
}
这是一个广泛的指南,如果您需要更具体的代码,请告诉我们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.