创建NotificationManager,点击进入ACTIVITY会创建新的activity
public void CreateNotification()
{
Intent mainIntent = new Intent(mContext, MainActivity.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent mainPendingIntent = PendingIntent.getActivity(mContext, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//获取NotificationManager实例
NotificationManager notifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
//实例化NotificationCompat.Builde并设置相关属性
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext)
//设置小图标
.setSmallIcon(R.drawable.ic_launcher_foreground)
//设置通知标题
.setContentTitle(mContext.getResources().getString(R.string.app_name))
//设置通知内容
.setContentText(mContext.getResources().getString(R.string.running))
.setOngoing(true)
.setContentIntent(mainPendingIntent);
//设置通知时间,默认为系统发出通知的时间,通常不用设置
//.setWhen(System.currentTimeMillis());
//通过builder.build()方法生成Notification对象,并发送通知,id=1
NotificationChannel channel = new NotificationChannel(tag, tag, NotificationManager .IMPORTANCE_LOW);
builder.setChannelId(tag);
notifyManager.createNotificationChannel(channel);
notifyManager.notify(0, builder.build());
}
public void CancleNotification()
{
NotificationManager notifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notifyManager.cancel(0);
}
要避免这个问题activity要设置
android:launchMode="singleTask"
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:excludeFromRecents="true"
android:launchMode="singleTask"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Activity一共有以下四种launchMode:
1.standard
2.singleTop
3.singleTask
4.singleInstance
launchMode 可以查看 https://blog.csdn.net/liuhe688/article/details/6754323/