美文网首页Android开发经验谈Android开发
前台服务无法点击跳转Activity的问题

前台服务无法点击跳转Activity的问题

作者: waiwaaa | 来源:发表于2020-06-07 16:31 被阅读0次

    1.PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);第4个参数必须为PendingIntent.FLAG_UPDATE_CURRENT,否则点击跳转一次后,第二次就无效了
    2.mBuildersetContentTextsetContentText至少设置一个,不然点击无效。

    1. 增加前台服务权限<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    public static final int NOTIFICATION_ID=1111;
    public static final String CHANNEL_ID = "xxxChannelId";
    public static final String CHANNEL_NAME = "xxx";
    
    @Override
        public void onCreate() {
            super.onCreate();
            Intent intent=new Intent(this, GoToActivity.class);
            PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);//1
    
            registerNotificationChannel();
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
            mBuilder.setSmallIcon(R.mipmap.logo)//必须要有
            .setContentIntent(pendingIntent)
            .setContentText("点击回到主界面")
            .setContentTitle(getResources().getString(R.string.app_name))
            //可选
            //.setSound(null)
            //.setVibrate(null)
            //...
            ;
    
            startForeground(NOTIFICATION_ID, mBuilder.build());
        }
    
    /**
         * 注册通知通道
         */
        private void registerNotificationChannel() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                NotificationChannel notificationChannel = mNotificationManager.getNotificationChannel(CHANNEL_ID);
                if (notificationChannel == null) {
                    NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                            CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                    //是否在桌面icon右上角展示小红点
                    channel.enableLights(false);
                    //小红点颜色
                    //channel.setLightColor(Color.RED);
                    //通知显示
                    //channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                    //是否在久按桌面图标时显示此渠道的通知
                    //channel.setShowBadge(true);
                    mNotificationManager.createNotificationChannel(channel);
                }
            }
        }
    

    相关文章

      网友评论

        本文标题:前台服务无法点击跳转Activity的问题

        本文链接:https://www.haomeiwen.com/subject/xmgvzhtx.html