看不到通知 - 安卓工作室



我试图发出通知,但单击按钮时没有通知,也没有错误。我启用了来自手机设置的通知。

我的代码


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class notification_page extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_page);
// Button notify = findViewById(R.id.notify);

}

NotificationManager manager;
int id =0;

public void notify(View view) {
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);
nBuilder.setContentTitle("Hello").setContentText("Notificaction!!").setSmallIcon(R.drawable.common_google_signin_btn_icon_dark);
manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(id,nBuilder.build());
id++;
}
public void cancel(View view) {
manager.cancelAll();
}
}

XML按钮android:onClick="notify"

Logcat 中没有错误

首先,您必须创建通知通道:

private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("1000", "channel_name", importance);
channel.setDescription("channel_description");
channel.setSound(null, null);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}

NotificationManager更改为:

NotificationManagerCompat manager;

然后像这样修改notify()函数:

public void notify(View view) {
createNotificationChannel(); //don't forget to create the channel
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, "1000"); //channelId should be same as the one created above
nBuilder.setContentTitle("Hello").setContentText("Notificaction!!").setSmallIcon(R.drawable.common_google_signin_btn_icon_dark);
manager = NotificationManagerCompat.from(getApplicationContext());
manager.notify(id, nBuilder.build());
id++;
}