使用以下代码时:
public class MainActivity extends AppCompatActivity {
private final static AtomicInteger notificationId = new AtomicInteger(0);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.notif )
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setContentTitle("Request Received")
.setContentText("new Notif")
.setAutoCancel(true)
.setDefaults(DEFAULT_LIGHTS);
mBuilder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_NO_CREATE));
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(notificationId.incrementAndGet(), mBuilder.build());
}
}
以下用户行为会创建一种不一致的通知方法:
我的代码中是否有导致此行为的内容? 预期会出现这种情况吗?
此外,我想提一下以下用例给出预期的通知行为:
此行为在Android 5和6上很明显,但尚未在Android 7上进行过测试。
答案 0 :(得分:0)
将代码移到onResume()方法
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.notif )
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setContentTitle("Request Received")
.setContentText("new Notif")
.setAutoCancel(true)
.setDefaults(DEFAULT_LIGHTS);
mBuilder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_NO_CREATE));
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(notificationId.incrementAndGet(), mBuilder.build());
答案 1 :(得分:0)
该问题似乎基于:“当使用此标志时,如果任务已经在您正在启动的活动上运行,则不会启动新活动;相反,当前任务将被带到屏幕的正面是它最后的状态。“关于“FLAG_ACTIVITY_NEW_TASK”。这导致“当前任务”在已经激活时被带到屏幕上。