【发布时间】:2018-06-20 07:17:53
【问题描述】:
我一直在网上寻找答案,但我自己却找不到答案,尽管阅读了官方 android 文档网站上的开发人员指南和来自互联网各地的代码 sn-ps。
我一直在练习在一个新的干净项目上创建通知,尽管创建了一个通知通道和通知本身,我仍然无法让它运行并收到一条消息:“无法在空通道上发布通知” .但是我正在创建频道,并将其分配给我的通知,就像它到处说的那样。我完全没有想法,老实说,我已经浏览堆栈至少几个小时了,每个答案看起来都一样,但它确实对我没有帮助,所以也许如果有人比初学者更好看我的代码可以告诉我我的代码有什么问题?这很烦人,因为通知是我正在进行的项目的重要组成部分,它阻止了我的前进。
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int NOTIFICATION_ID = 1;
private static final String NOTIFICATION_CHANNEL_ID = "my_notification_channel";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
findViewById(R.id.buckysButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
createNotification(view);
}
});
}
public void createNotification(View view){
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
nm.createNotificationChannel(notificationChannel);
}
notification.setSmallIcon(R.drawable.ic_priority_high_black_24px);
notification.setTicker("Ticker");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Title");
notification.setContentText("Body Body Body Body Body Body Body Body Body ");
notification.setChannel(NOTIFICATION_CHANNEL_ID);
notification.build();
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
nm.notify(NOTIFICATION_ID, notification.build());
}}
顺便说一句,我正在为 Android 最低级别 5.1 进行开发,我一直想知道是否真的有必要在我的应用程序中放置通道,但我还是这样做了,因为当我尝试在没有它们的情况下这样做时,我仍然得到完全相同的错误。
编辑:我仍在努力解决这个问题。我是否必须在 gradle 文件中做一些事情才能将两个参数传递给 NotificationCompat.Builder 构造函数?不管我做什么,它都不会让我这样做,我认为这是这里的主要问题。
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
不为我做,它仍然不想将 channel_id 作为参数。
【问题讨论】:
标签: android notifications sdk mobile-application channels