我有一个Android应用程序,正在其中尝试实现Firebase推送通知。我在firebase控制台中正确安装了项目,并下载并找到了json文件。我的通知代码如下。
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final int MESSAGE_NOTIFICATION_ID = 6545;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
RemoteMessage.Notification notification = remoteMessage.getNotification();
assert notification != null;
String notificaitonTitle = "";
Map data = null;
try {
data = remoteMessage.getData();
notificaitonTitle = data.get("title").toString();
} catch (Exception e) {
e.printStackTrace();
}
if (remoteMessage.getData().size() > 0) {
assert data != null;
createNotification(notificaitonTitle, data.get("desc").toString());
}
}
private void createNotification(String notificationTitle, String desc) {
Context context = getBaseContext();
Intent intent = new Intent(this, SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
String CHANNEL_ID = "channel_01";
String CHANNEL_NAME = "channel_01";
int sound_notification = context.getSharedPreferences("setting", MODE_PRIVATE).getInt("sound_notification", 1);
Uri soundTest = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/raw/sound" + (sound_notification));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int notifyID = 1;
int importance = NotificationManager.IMPORTANCE_HIGH;
Notification notification =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(notificationTitle)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setChannelId(CHANNEL_ID)
.setSound(soundTest)
.build();
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
mNotificationManager.notify(notifyID, notification);
}
}
else {
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID);
notificationBuilder
.setSmallIcon(R.drawable.ic_launcher).setContentTitle(notificationTitle)
.setSound(soundTest)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null) {
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, notificationBuilder.build());
}
}
}
}
我的构建工具和目标如下所示
compileSdkVersion 27
buildToolsVersion "27.0.3"
我在我的项目中实现了如下所示的firebase库。
implementation 'com.google.firebase:firebase-messaging:17.1.0'
implementation 'com.google.firebase:firebase-core:16.0.1'
让我知道是否有人可以建议我我的代码有什么问题。我从最近四个小时开始尝试,但找不到合适的解决方案。
谢谢