【问题标题】:How to make it work NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);如何使其工作 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
【发布时间】:2018-07-10 03:05:08
【问题描述】:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

显示错误:

Builder中的Builder(Context)不能应用到(FirebaseMessagingService, java.lang.String)

帮我解决这个问题。

试过 Notification.Builder notificationBuilder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

但它不适用于 API 23 和 API 27。

这里是代码

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.NotificationCompat;

import com.google.firebase.messaging.RemoteMessage;


public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        String notification_title = remoteMessage.getData().get("title");
        String notification_msg = remoteMessage.getData().get("body");
        String from_user_id = remoteMessage.getData().get("from_user_id");
        String click_action = remoteMessage.getData().get("click_action");

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "channel_id_01";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);

            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.BLUE);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);

            notificationManager.createNotificationChannel(notificationChannel);
        }


        Intent intent = new Intent(click_action);
        intent.putExtra("user_id", from_user_id);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

        notificationBuilder.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).setWhen(System.currentTimeMillis()).setSmallIcon(R.drawable.logo1).setPriority(Notification.PRIORITY_MAX).setContentTitle(notification_title).setContentText(notification_msg).setContentInfo("Info").setContentIntent(pendingIntent);


        int mNotificationId = (int) System.currentTimeMillis();
        notificationManager.notify(mNotificationId, notificationBuilder.build());
    }
}

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.android.gabwithus"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
    implementation 'com.android.support:design:28.0.0-alpha3'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.google.firebase:firebase-auth:16.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation 'com.google.firebase:firebase-database:16.0.1'
    implementation 'com.google.firebase:firebase-messaging:17.1.0'
    implementation 'com.android.support:support-v4:28.0.0-alpha3'
    implementation 'com.google.firebase:firebase-storage:15.0.0'
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.0'
    testImplementation 'junit:junit:4.12'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.firebaseui:firebase-ui-database:2.0.1'
    implementation 'com.squareup.okhttp:okhttp:2.5.0'
    implementation 'id.zelory:compressor:2.1.0'
    implementation 'com.android.support:support-media-compat:28.0.0-alpha3'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'de.hdodenhof:circleimageview:2.2.0'
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.5.1'
    implementation 'com.facebook.fresco:fresco:1.5.0'

}

apply plugin: 'com.google.gms.google-services'
configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '25.3.0'
            }
        }
    }
}

【问题讨论】:

  • 你能用你面临的错误更新你的问题吗?
  • 我已经测试了您的代码及其在 API 23 和 26 上的工作。
  • 我也在 API 27 中尝试
  • Builder 中的 Builder (Context) 无法应用于 (FirebaseMessagingService, java.lang.String) 出现此错误

标签: android firebase push-notification firebase-cloud-messaging


【解决方案1】:

尝试使用这个,我认为你的问题在这里:details.useVersion '25.3.0'

     configurations.all {
        resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '27.1.0'
            }
        }
    }

}

【讨论】:

  • @VijayaAditya 如果它有效,请为答案投票。
  • 我的声望不够
  • 你不需要声誉来接受它作为答案。
【解决方案2】:

问题是您使用的是import android.support.v7.app.NotificationCompatv7.app.NotificationCompat 实际上已在 revision 27.0.0 中删除,并且从未更新以支持通知通道。

您应该删除该行并导入android.support.v4.app.NotificationCompat,它确实支持通知通道。

【讨论】:

    【解决方案3】:

    它在所有 api 中的工作试试这个:

     public void sendNotification(String messageBody) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_enable_notification_icon)
                        .setColor(Color.parseColor("#5878f2"))
                        .setContentTitle(getString(R.string.app_name))
                        .setContentText(messageBody)               
                        .setAutoCancel(true);
    
        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.putExtra("message",messageBody);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);
    
        if(Build.VERSION_CODES.O <= Build.VERSION.SDK_INT) {
            builder.setChannelId(createNotificationChannel());
        }
    
        Notification notification = builder.build();
        notificationManager.notify(211, notification);
    }
    
     @RequiresApi(api = Build.VERSION_CODES.O)
    private String createNotificationChannel(){
        String channelId = "demo";
        String channelName = "My demo";
        NotificationChannel mChannel = new NotificationChannel(channelId,channelName, NotificationManager.IMPORTANCE_NONE);
        mChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
    
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (mNotificationManager != null) {
            mNotificationManager.createNotificationChannel(mChannel);
        }
        return channelId;
    }
    

    【讨论】:

    • builder.setChannelId(createNotificationChannel());在这一行 setChannelId 显示错误
    • import android.support.v4.app.NotificationCompat;@VijayaAditya替换你的import android.support.v7.app.NotificationCompat;
    【解决方案4】:

    Android O 及以上版本需要通知通道。这是 you.getRequestCode 方法的一个工作示例,用于不同的通知,因此它们不会被替换。您也可以使用任何数字。如果你使用相同的号码通知会自动替换,所以我使用随机数生成器。

      private static int getRequestCode() {
        Random rnd = new Random();
        return 100 + rnd.nextInt(900000);
    }
    
    
      PendingIntent pendingIntent = PendingIntent.getActivity(this, getRequestCode()  /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);
    
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
                        R.mipmap.ic_launcher))
                .setContentTitle(neplaiTile) // use your own title
                .setContentText(message)    // use your own message
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent)
                .setPriority(Notification.PRIORITY_MAX)
                .setBadgeIconType(Notification.BADGE_ICON_SMALL);
    
    
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            assert notificationManager != null;
            notificationBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        assert notificationManager != null;
        notificationManager.notify(getRequestCode() /* Request Code */, notificationBuilder.build());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      相关资源
      最近更新 更多