gpt4 book ai didi

android - 在 Android 中创建通知应用程序?

转载 作者:行者123 更新时间:2023-11-29 17:57:12 25 4
gpt4 key购买 nike

我想创建一个示例项目以在单击按钮时显示通知,然后当用户选择它时在我的应用程序中打开该 Activity 或在选择它时打开一个 url。我做了一些事情,但我无法完成该功能。

首先我在使用它时遇到错误:@SuppressLint("NewApi")

如果我不使用它,我会在此处收到错误

Notification noti = new Notification.Builder(this)

Activity 代码

public class NotificationExample extends Activity implements OnClickListener{

private Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_example);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);

}


@SuppressLint("NewApi")
@Override
public void onClick(View v) {
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification noti = new Notification.Builder(this)
.setTicker("Ticker Title")
.setContentTitle("Content Title")
.setContentText("Notification content.")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent).getNotification();
noti.flags=Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
}
}

为什么我必须使用它:

`@SuppressLint("NewApi")` 

在我的代码中?我没有收到通知声音。请建议我必须对我的代码进行哪些更改。

最佳答案

要为您的通知添加声音,请使用以下简短代码。

Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(notificationSound);

完整代码

PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
0);
Builder builder = new NotificationCompat.Builder(context)
.setTicker("Ticker Title").setContentTitle("Content Title")
.setContentText("Notification content.")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent);
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(notificationSound);
Notification noti = builder.build();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);

contextApplication Context 使用 getApplicationContext() 获取。

编辑

要使用通知打开浏览器的任何链接,请使用以下代码。

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.google.com"));

将此 Intent 传递给您的PendingIntent

关于android - 在 Android 中创建通知应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18526963/

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