我通过如下更新代码解决了问题:
@Override
public void onPause() {
super.onPause();
if (!isNotificationShown)
createNotification();
}
@Override
public void onResume() {
super.onResume();
if (isNotificationShown) {
clearNotification();
}
}
@Override
public void onDestroy() {
super.onDestroy();
clearNotification();
}
//Create Notification
private void createNotification() {
isNotificationShown = true;
createNotificationChannel();
// Create an explicit intent for an Activity in your app
Intent intent = new Intent(IncomingCallActivity.this, IncomingCallActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.pref_noti_icon)
.setContentTitle(this.getResources().getString(R.string.app_name))
.setContentText(this.getResources().getString(R.string.notification_return_to_call))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private void clearNotification() {
isNotificationShown = false;
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager!=null)
notificationManager.cancel(NOTIFICATION_ID);
}
也不要忘记设置
android:launchMode="singleTop"
属于
活动
在里面
AndroidManifest。xml
文件