没有服务的持续通知

时间:2013-11-21 03:13:49

标签: android android-intent android-service alarmmanager

我目前正在开发一个应用程序,它使用AlarmManager启动每隔x分钟向用户显示的意图。我还想在状态栏中显示持续通知,显示下一次弹出窗口之前的时间。有没有办法在没有后台服务的情况下显示持久通知。如果没有,那么停止使用AlarmManager并且每隔x分钟只使用服务弹出意图是否有意义?

基本上我需要确保每x分钟启动一次意图,即使手机内存不足并且通知仍保留在状态栏中。我还希望能够点击通知来重置倒计时的计时器。实现这些目标的最佳方法是什么?

谢谢, 森

1 个答案:

答案 0 :(得分:1)

要生成通知,请尝试以下操作:

private void generateNotification(Context context, String message) {

int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
String appname = context.getResources().getString(R.string.app_name);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Notification notification;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, myactivity.class), 0);

// To support 2.3 os, we use "Notification" class and 3.0+ os will use
// "NotificationCompat.Builder" class.
 if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
 notification = new Notification(icon, message, 0);
 notification.setLatestEventInfo(context, appname, message,
 contentIntent);
 notification.flags = Notification.FLAG_AUTO_CANCEL;
 notificationManager.notify(0, notification);

 } else {
 NotificationCompat.Builder builder = new NotificationCompat.Builder(
 context);
 notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(0)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();

 notificationManager.notify(0 , notification);
}
}

希望这有帮助。

相关问题