0

我正在尝试使用 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);

那么有谁知道为什么这不会显示任何错误?

4

1 回答 1

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);

}
}

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

于 2013-11-06T07:55:46.147 回答