我尝试发出通知,但单击按钮时没有任何通知,也没有错误。 我从手机设置中启用了通知。
我的代码
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 中没有错误
最佳答案
首先,您必须创建通知 channel :
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 管理器;
然后修改您的 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++;
}
关于java - 看不到通知 - Android Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61718182/