在Android上使用Cordova。如何显示背景通知?

时间:2013-11-05 20:14:50

标签: android cordova notifications

我正在尝试使用Android显示通知。以下代码不显示任何内容。我错过了什么吗?不会抛出任何错误并且代码会执行,但我看不到任何对话框或任何指示通知的内容。

NotificationManager mNotificationManager = (NotificationManager) 
              this.getSystemService(android.content.Context.NOTIFICATION_SERVICE); 


      Notification n  = new Notification.Builder(this.getApplicationContext())
        .setContentTitle("Socket Message Received")
        .setContentText("My Application")
        .setSmallIcon(com.mypackage.app.R.drawable.icon)
        .build();

      mNotificationManager.notify(5, n);

或者当我直接从Cordova插件中调用它时

NotificationManager mNotificationManager = (NotificationManager) 
                  cordova.getActivity().getApplicationContext().getSystemService(android.content.Context.NOTIFICATION_SERVICE); 


          Notification n  = new Notification.Builder(cordova.getActivity().getApplicationContext())
            .setContentTitle("Socket Message Received")
            .setContentText("My Application")
            .setSmallIcon(com.mypackage.app.R.drawable.icon)
            .build();

          mNotificationManager.notify(CM_NOTIFICATION_ID.hashCode(), n);

所以有人都知道为什么没有错误会显示什么?

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

}
}

希望这会有所帮助。这对我有用。