Android中的新闻通知

时间:2013-10-14 07:07:25

标签: android push-notification android-notifications

我正在开发应用程序,我需要实现新闻通知的功能。

例如, NDTV新闻应用:只要有新消息就会发出通知。它是如何发生的?

有人能为我提供解决方案示例吗?

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用此代码:

    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((int) when , notification);

    }

}