Android日常

点击Notification跳转指定的activity

2020-07-08  本文已影响0人  wasdzy111

1、代码如下:

       //适配8.0service
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel mChannel = null;
            mChannel = new NotificationChannel(CHANNEL_ID_STRING, "xxx", NotificationManager.IMPORTANCE_HIGH);
            mChannel.enableVibration(false);//禁用震动
            mChannel.setSound(null, null);//设置没有声音
            notificationManager.createNotificationChannel(mChannel);
            PendingIntent pendingIntent = toMainActivity();
            Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING)
                    .setContentText("xxx运行中")
                    .setContentTitle("xxx")
                    .setAutoCancel(false)
                    .setOngoing(true)
                    .setSmallIcon(R.mipmap.ic_logo)
                    .setContentIntent(pendingIntent)
                    .setPriority(PRIORITY_MAX)
                    .build();
            startForeground(1, notification);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {     //如果API大于18,需要弹出一个可见通知
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.mipmap.ic_logo);
            builder.setContentTitle("xxx");
            builder.setContentText("xxx运行中");
            PendingIntent pendingIntent = toMainActivity();
            builder.setContentIntent(pendingIntent);
            startForeground(NOTICE_ID, builder.build());

            // 如果觉得常驻通知栏体验不好
            // 可以通过启动CancelNoticeService,将通知移除,oom_adj值不变
            //Intent intent = new Intent(this, CancelNoticeService.class);
            //StartServiceUtil.start(this, intent);
        } else {
            startForeground(NOTICE_ID, new Notification());
        }

2、跳转代码

 private PendingIntent toMainActivity() {
        //点击广播监听
        Intent intentClick = null;
        try {
            intentClick = new Intent(this, Class.forName("com.xxx.MainActivity"));    
            //如果跳转的activity 是一个普通的设置FLAG_ACTIVITY_NEW_TASK即可,
            //如果是一个singletask activity 则需要添加FLAG_ACTIVITY_CLEAR_TOP ,否则启动可能失败
            intentClick.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intentClick.addCategory("android.intent.category.LAUNCHER");
            intentClick.setAction("android.intent.action.MAIN");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return PendingIntent.getActivity(this, 0, intentClick, 0);
    }
上一篇 下一篇

猜你喜欢

热点阅读