gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:06 25 4
gpt4 key购买 nike

这是我的代码:


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; 表示它未被使用。

最佳答案

如果你想开发低于 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);
}

您可以像这样在 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);
}
}
}

关于android - 为什么 Eclipse 无法识别 Notification.Builder 类中的 build() 方法来返回 Notification 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11372055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com