通知不通知

时间:2018-12-14 08:01:58

标签: android push-notification notifications notify paho

我正在使用paho MQTT client依赖项制作MQTT客户端应用。

在后台服务中实现代码。一切正常,除了“通知”不起作用!

服务代码段为here

我的代码出现在TimeDisplayTimerTask内部类内部。

此代码位于回调函数中:

            @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            mIntent = new Intent(getApplicationContext(), MainActivity.class);
            mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, mIntent, 0);

            createNotificationChannel();

            Toast.makeText(getApplicationContext(),"A message received : "+ new String(message.getPayload()),Toast.LENGTH_SHORT).show();

            vibrator.vibrate(500);
            myRingtone.play();
            mBuilder .setContentTitle("Message received at : " + mTopic)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setContentText("Message : "+ new String(message.getPayload()));
            mNotificationManager.notify(0, mBuilder.build());
        }

此代码创建了一个通知渠道(如Google开发人员指南所述):

借助此answer发布。

private void createNotificationChannel() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String chanel_id = "3000";
            CharSequence name = "Mqtt message";
            String description = "Message arrived";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel mChannel = new NotificationChannel(chanel_id, name, importance);
            mChannel.setDescription(description);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.BLUE);
            mNotificationManager = getSystemService(NotificationManager.class);
            if (mNotificationManager != null) {
                mNotificationManager.createNotificationChannel(mChannel);
            }

            mBuilder = new NotificationCompat.Builder(getApplicationContext(), chanel_id);
        }
        else
        {
            mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mBuilder = new NotificationCompat.Builder(getApplicationContext());
        }

    }

当它收到一条消息时,会显示一条吐司消息,其中包含该消息。 但这不会推送通知。

已检查的应用和通知,允许所有通知。

已解决: 必须调用setter方法.setSmallIcon才能成功构建通知。

哪个对我不重要

0 个答案:

没有答案