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

And*_*ndy 5 eclipse android 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);
Run Code Online (Sandbox Code Playgroud)

它有效,但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;
Run Code Online (Sandbox Code Playgroud)

请注意,import android.app.Notification.Builder;它说它没有被使用.

val*_*dak 2

如果您想开发低于11版本的SDK,您可以使用以下代码代替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);      
}
Run Code Online (Sandbox Code Playgroud)

您可以在 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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)