Android在任意位置由Notification跳向指定fragment

前段时间在项目中遇到的需求,点击通知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这个方法,所以浪费时间挺长的,算是长知识了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值