为什么Eclipse无法识别Notification.Builder类中的build()方法以返回Notification对象?

时间:2012-07-07 03:35:46

标签: android eclipse deprecated notificationmanager

这是我的代码:


NotificationManager mNotificationManager = (NotificationManager) c.getSystemService(ns);

    //Instantiate the notification

    CharSequence tickerText = "Hello";
    long when = System.currentTimeMillis();
    Notification.Builder builder = new Notification.Builder(c)
                                .setTicker(tickerText)
                                .setWhen(when)
                                .setContentTitle("Test Notification")
                                .setContentText(arg1.getStringExtra("info"))
                                .setSmallIcon(R.drawable.ic_launcher)
                                .setAutoCancel(true);
    Notification notification = builder.getNotification();
    mNotificationManager.notify(88, notification);

它可以找到,但不推荐使用Notification notification = builder.getNotification();。正如我应该做的那样Notification notification = builder.build();。 问题是Eclipse没有认识到它,这意味着它不会让我编译。该文档清楚地表明build()存在并且是首选方法,但它不适合我。我想使用不推荐使用的代码,因此非常感谢任何帮助。

进口


import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

请注意import android.app.Notification.Builder;说它未被使用。

2 个答案:

答案 0 :(得分:2)

如果您希望开发版本SDK 较低而不是11,则可以使用此代码代替 android.app.Notification.Builder 类进行创建通知:

private void createNotification(){
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.ic_launcher, "Hello", System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, YourActivity.class);

    Random r = new Random();
    int notificationId = r.nextInt();
    notificationIntent.putExtra("n_id", notificationId);
    PendingIntent contentIntent = PendingIntent.getActivity(this, notificationId, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.setLatestEventInfo(this, "Party", "Welcome!", contentIntent);
    mNotificationManager.notify(notificationId, notification);      
}

您可以在YourActivity中取消此通知,如下所示:

public class YourActivity extends Activity{ 

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity);

    int notificationId = getIntent().getIntExtra("n_id", -1);

    if (notificationId!=-1) {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(notificationId);
    }
  }
}

答案 1 :(得分:1)

只有在您针对不具备必需方法/ api 的版本编译应用代码时才会发生这种情况(在您的情况下为build())。

如果您正在编译的版本中没有版本,我建议您使用更高版本的Android进行编译,为了向后兼容,您在清单中总是有最小sdk版本

由于