1

我正在为 android 创建一个用于通知的小应用程序。

但它给出了通知类错误中的错误(支持 11 或 16 的 API 级别)。然后我尝试使用 NotificationCompat 类,但它显示资源无法解析为一种类型,而我import package import android.support.v4.app.NotificationCompat.Builder;

换句话说,如果我使用 Notification 类,那么它会给出 API 级别错误,如果我使用 NotificationCompat,那么它会给出资源错误。如何解决这两个错误?

 public void createNotification(View view) {
    // Prepare intent which is triggered if the
    // notification is selected
    Intent intent = new Intent(this, NotificationReceiverActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
    // Context context=new Context();
    // Build notification
    // Actions are just fake
     NotificationCompat.Builder noti = new NotificationCompat.Builder(this)
    .setContentTitle("New mail from " + "star.ankit90@gmail.com")
    .setContentText("Subject").setSmallIcon(R.drawable.ic_launcher)
    .setContentIntent(pIntent)
    .addAction(R.drawable.ic_launcher, "Call", pIntent)
    .addAction(R.drawable.ic_launcher, "More", pIntent)
    .addAction(R.drawable.ic_launcher, "And more", pIntent).build();
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // Hide the notification after its selected
    noti.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, noti);
}
4

1 回答 1

1

我在使用您的代码时遇到了编译错误。

此固定代码编译成功:

// Prepare intent which is triggered if the
    // notification is selected
    Intent intent = new Intent(this, NotificationReceiverActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

    // Build notification
    // Actions are just fake
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setContentTitle("New mail from " + "star.ankit90@gmail.com")
    .setContentText("Subject").setSmallIcon(R.drawable.ic_launcher)
    .setContentIntent(pIntent)
    .addAction(R.drawable.ic_launcher, "Call", pIntent)
    .addAction(R.drawable.ic_launcher, "More", pIntent)
    .addAction(R.drawable.ic_launcher, "And more", pIntent).build();
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Hide the notification after its selected
    Notification notification = builder.build();

    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, notification);

也许它会为你工作。如果不是堆栈跟踪可以提供帮助。

于 2013-01-29T07:20:54.517 回答