前段时间在项目中遇到的需求,点击通知notification要打开一个fragment页面,并且主Activity的加载模式时singTask,就很头疼。
搞了半天。在这里将解决方案记下来:
NotificationUtil:
NotificationCompat.Builder builder builder = new NotificationCompat.Builder(context);
/**
*Notification布局设置
*/
//首先,带参跳到主Activity上
Intent toFragment= new Intent(context, MainActivity.class);
intent.putExtra("toValue", "跳转fragment");
PendingIntent pend = PendingIntent.getActivity(context,201,toFragment,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pend);
builder.setFullScreenIntent(pend, true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(3, builder.build());
主Activity:
@Override
protected void onNewIntent(Intent intent) {
//点击通知栏到主Activity时 会执行这个方法
getNotify(intent);
setIntent(intent);
}
private void getNotify(Intent intent) {
//拿到参数后 首先判断是不是为空
String value = intent.getStringExtra("toValue");
if (!TextUtils.isEmpty(value)) {
switch (value) {
//在进行判断需要做的操作
case "跳转fragment":
//在activity中切换fragment
break;
}
}
//做完操作以后必须将toValue的值初始化
intent.putExtra("toValue", "");
super.onNewIntent(intent);
}
现在看着也很简单,但是当时遇到问题的时候还不知道Activity有onNewIntent这个方法,所以浪费时间挺长的,算是长知识了。