Android Notification 震动,声音控制(兼容低版本)

public class MyApplication extends MyApp {

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        TIMManager.getInstance().setOfflinePushListener(new TIMOfflinePushListener() {

            @Override
            public void handleNotification(TIMOfflinePushNotification var1) {

            }
        });
        TIMManager.getInstance().addMessageListener(new TIMMessageListener() {
            @Override
            public boolean onNewMessages(List<TIMMessage> msgs) {
                showNotice(msgs);
                return false;
            }
        });
        notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    }


    public void showNotice(List<TIMMessage> msgs) {
        if (msgs.size() > 0) {
            final TIMMessage timMessage = msgs.get(msgs.size() - 1);
            List<String> users = new ArrayList<>();
            users.add(timMessage.getSender());
            if (users.size() > 0)
                TIMFriendshipManager.getInstance().getUsersProfile(users, false, new TIMValueCallBack<List<TIMUserProfile>>() {
                    @Override
                    public void onError(int code, String desc) {
                        //错误码 code 和错误描述 desc,可用于定位请求失败原因
                        //错误码 code 列表请参见错误码表
                    }

                    @Override
                    public void onSuccess(List<TIMUserProfile> result) {
                        if (result.size() > 0) showNotice(timMessage, result.get(0));
                    }
                });
        }

    }

    private void showNotice(TIMMessage timMessage, TIMUserProfile timUserProfile) {
        MessageInfo messageInfo = MessageInfoUtil.TIMMessage2MessageInfo(timMessage, false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setChannerl();
        }
        createNotification(timUserProfile.getNickName(), String.valueOf(messageInfo.getExtra()));
    }

    public boolean getSound() {
        if (!TextUtils.isEmpty(msg_notic2) && msg_notic2.equals("1"))
            return true;
        else
            return false;

    }


    public boolean getVibrate() {
        if (!TextUtils.isEmpty(msg_notic1) && msg_notic1.equals("1")) {
            return true;
        } else
            return false;

    }

    long[] pattern = new long[]{1000, 1000, 1000, 1000, 1000};
    String beforeChannelId = "1";
    NotificationManager notificationManager;

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(boolean isVibrate, String channelId, String channelName,
                                           int
                                                   importance) {
        if (!TextUtils.isEmpty(beforeChannelId)) {
            //先删除之前的channelId对应的消息通道.
            notificationManager.deleteNotificationChannel(beforeChannelId);
        }
        //重新new一个消息通道。
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        //是否震动
        if (getVibrate()) {
            // 设置通知出现时的震动(如果 android 设备支持的话)
            channel.enableVibration(true);
            channel.setVibrationPattern(pattern);
        } else {
            // 设置通知出现时不震动
            channel.enableVibration(false);
            channel.setVibrationPattern(new long[]{0});
        }
        if (getSound()) {
            // 设置通知出现时的震动(如果 android 设备支持的话)
            channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), Notification.AUDIO_ATTRIBUTES_DEFAULT);
        } else {
            // 设置通知出现时不震动
            channel.setSound(null, null);
        }
        notificationManager.createNotificationChannel(channel);
    }

    private void createNotification(String nickName, String content) {


        Intent intent = new Intent(this, MainActivity.class);
        /*
         * 调用PendingIntent的静态放法创建一个 PendingIntent对象用于点击通知之后执行的操作,
         * PendingIntent可以理解为延时的Intent,在这里即为点击通知之后执行的Intent
         * 这里调用getActivity(Context context, int requestCode, Intent intent, int flag)方法
         * 表示这个PendingIntent对象启动的是Activity,类似的还有getService方法、getBroadcast方法
         */
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        sendNotification(nickName, content, pi);
    }

    public void sendNotification(String title, String content, PendingIntent pi) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification notification = getChannelNotification
                    (title, content, pi).build();
            notificationManager.notify(1, notification);
        } else {
            Notification notification = getNotification_25(title, content, pi).build();
            notificationManager.notify(1, notification);
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    public Notification.Builder getChannelNotification(String title, String content, PendingIntent pi) {
        return new Notification.Builder(getApplicationContext())
                .setContentTitle(title) // 创建通知的标题
                .setChannelId(channelId)
                .setContentText(content) // 创建通知的内容
                .setSmallIcon(R.mipmap.ic_launcher) // 创建通知的小图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                        R.mipmap.ic_launcher)) // 创建通知的大图标
                /*
                 * 首先,无论你是使用自定义视图还是系统提供的视图,上面4的属性一定要设置,不然这个通知显示不出来
                 */
                .setWhen(System.currentTimeMillis()) // 设定通知显示的时间
                .setContentIntent(pi) // 设定点击通知之后启动的内容,这个内容由方法中的参数:PendingIntent对象决定
                //.setPriority(NotificationCompat.PRIORITY_MAX) // 设置通知的优先级
                .setAutoCancel(true); // 设置点击通知之后通知是否消失
    }

    public NotificationCompat.Builder getNotification_25(String title, String content, PendingIntent pi) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "1")
                .setContentTitle(title) // 创建通知的标题
                .setContentText(content) // 创建通知的内容
                .setSmallIcon(R.mipmap.ic_launcher) // 创建通知的小图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                        R.mipmap.ic_launcher)) // 创建通知的大图标


                /*
                 * 首先,无论你是使用自定义视图还是系统提供的视图,上面4的属性一定要设置,不然这个通知显示不出来
                 */
                .setWhen(System.currentTimeMillis()) // 设定通知显示的时间
                .setContentIntent(pi) // 设定点击通知之后启动的内容,这个内容由方法中的参数:PendingIntent对象决定
//                .setPriority(NotificationCompat.PRIORITY_MAX) // 设置通知的优先级
                .setAutoCancel(true);
        if (getSound() && getVibrate())
            builder.setDefaults(Notification.DEFAULT_ALL).setVibrate(pattern).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        else {
            if (getVibrate()) {
                builder.setDefaults(Notification.DEFAULT_VIBRATE).setVibrate(pattern);
            } else if (getSound()) {
                builder.setDefaults(Notification.DEFAULT_SOUND).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            } else builder.setDefaults(Notification.FLAG_ONLY_ALERT_ONCE);
        }
        return builder;// 设置点击通知之后通知是否消失
    }

    String channelId;
    int i;

    private void setChannerl() {

        channelId = "chat" + i++;//消息通道的id,以后可以通过该id找到该消息通道
        String channelName = "聊天消息" + i;//消息通道的name


        // .具体的请自行百度。作用就是优先级的不同。可以导致消息出现的形式不一样。
        // MAX是会震动并且出现在屏幕的上方。设置优先级为low或者min时。来通知时都不会震动,
        // 且不会直接出现在屏幕上方
        createNotificationChannel(true, channelId, channelName, IMPORTANCE_HIGH);
        beforeChannelId = channelId;

    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值