在真实设备中显示通知的问题
problem in show a notification in in real device
大家好,我为 android 应用程序创建了一个通知,我的代码在虚拟设备中有效但在真实设备中无效,请帮助我。
public void onClick(View v){
try {
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setSmallIcon(R.mipmap.smile);
builder.setShowWhen(true);
builder.setContentText("This is my first notification");
builder.setContentTitle("My Notification");
builder.setAutoCancel(true);
Intent i = new Intent(MainActivity.this, SecondClass.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);
stackBuilder.addParentStack(SecondClass.class);
stackBuilder.addNextIntent(i);
PendingIntent pi = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, builder.build());
Toast.makeText(getApplicationContext(),"Notification showed!",Toast.LENGTH_LONG).show();
}
catch (Exception e){
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
原因可能是您的模拟器低于 api 级别 26(oreo) 而您的 phone,您所说的真实设备高于或等于 api 级别26,从 oreo 开始,您需要创建通知渠道才能显示 notifications.For 更多信息阅读 here.
大家好,我为 android 应用程序创建了一个通知,我的代码在虚拟设备中有效但在真实设备中无效,请帮助我。
public void onClick(View v){
try {
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setSmallIcon(R.mipmap.smile);
builder.setShowWhen(true);
builder.setContentText("This is my first notification");
builder.setContentTitle("My Notification");
builder.setAutoCancel(true);
Intent i = new Intent(MainActivity.this, SecondClass.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);
stackBuilder.addParentStack(SecondClass.class);
stackBuilder.addNextIntent(i);
PendingIntent pi = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, builder.build());
Toast.makeText(getApplicationContext(),"Notification showed!",Toast.LENGTH_LONG).show();
}
catch (Exception e){
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
原因可能是您的模拟器低于 api 级别 26(oreo) 而您的 phone,您所说的真实设备高于或等于 api 级别26,从 oreo 开始,您需要创建通知渠道才能显示 notifications.For 更多信息阅读 here.