gpt4 book ai didi

java - 无法让android创建通知

转载 作者:行者123 更新时间:2023-11-29 22:45:59 27 4
gpt4 key购买 nike

我试图让 android 在按下按钮时显示通知。我遵循了在线教程,但按下按钮时没有任何反应。在线查看我找不到任何可以表明问题所在的信息,而且我是 android 的新手。

我有一节课


import android.app.Notification;
import android.os.Bundle;
import android.app.NotificationManager;
import android.view.View;
import android.content.Context;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void sendNotification(View view) {

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "M_CH_ID");

notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
.setContentTitle("Default notification")
.setContentText("Random words")
.setContentInfo("Info");

NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
}
}

和一种布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendNotification"
android:text="@string/do_it" />

</LinearLayout>

如果有人可以向我解释问题是什么,或者可以将我链接到截至 API 29 的准确教程,我将不胜感激。

最佳答案

https://developer.android.com/training/notify-user/channels

  public void sendNotification(View view)  
{
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel =
new NotificationChannel("M_CH_ID", "M_CH_ID", NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("Test");
nm.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "M_CH_ID");

notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_add)
.setTicker("Hearty365")
.setContentTitle("Default notification")
.setContentText("Random words")
.setContentInfo("Info");

nm.notify(1, notificationBuilder.build());
}

关于java - 无法让android创建通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58491317/

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