我正在尝试让我的应用创建通知,但此代码会给我编译错误:
public void makeRing(Context context, boolean notify)
{
if (notify)
{
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
//.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on (first number)
mNotificationManager.notify(5954, mBuilder.build());
}
这是直接从Android开发者网站获取的代码。错误位于“TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);”的行,其中create带有下划线,并且表示'方法create(Context)未定义为TaskStackBuilder类型。
另外,在最后一行中,build()带有下划线,并且表示'NotificationCompat.Builder类型的方法build()未定义。
我如何解决这些问题?
答案 0 :(得分:3)
使用支持库时遇到了同样的问题。它似乎没有实现那些方法。以下是有效的代码:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_action_search)
.setContentTitle("New search")
.setContentText("Que hay de nuevo, viejo");
Intent resultIntent = new Intent(this, Temporal.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.from(this);
stackBuilder.addParentStack(Temporal.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(112, builder.getNotification());
更改
TaskStackBuilder stackBuilder = TaskStackBuilder.from(this);
而不是
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
和
manager.notify(112, builder.getNotification());
而不是
manager.notify(112, mBuilder.build());
<强> EDITED 强>
更好的解决方案:只需下载最新的Android支持库。
答案 1 :(得分:0)
您可能尚未下载所需版本的支持库。您可以看到HERE所有版本,并找出您需要的版本。
我认为这是包含通知更改的最新版本:
支持包,修订版10(2012年8月)
v4支持库的更改:
Added support for notification features introduced in Android 4.1 (API level 16) with additions to NotificationCompat.
但你可以下载最新的版本,只是为了确定。