【问题标题】:Can I set a custom ringtone and vibration pattern for a firebase notification?我可以为 Firebase 通知设置自定义铃声和振动模式吗?
【发布时间】:2018-12-03 16:20:42
【问题描述】:

最近我开始编写我的第一个 android 项目,其中包括 Firebase Cloud Messaging。我使用 Android SDK 21 (Android 5)。

我的目的是让用户选择,应该播放哪种铃声以及设备是否应该振动。为此,我创建了一个帮助类 SettingsHandler,它可以像这样访问用户设置:

public synchronized static Uri getRingtoneUri(Context context) {
    Sharedpreferences prefs = context.getSharedPreferences("table_name", Context.MODE_PRIVATE);
    return Uri.parse(prefs.getString("ringtone_key"), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString());
}

public synchronized static boolean shouldVibrateOnPush(Context context) {
    SharedPreferences prefs = context.getSharedPreferences("table_name", Context.MODE_PRIVATE);
    return prefs.getBoolean("vibration_flag", true);
}

因此,当我收到来自 Firebase 的通知时,我想设置用户可以使用上述方法设置的声音和振动模式。

为了得到这个,我覆盖了 MyFirebaseMessagingService 中的 onMessageReceived 方法,它扩展了 - 谁期望这个 - FirebaseMessagingService

public void onMessageReceived(RemoteMessage msg) {
    super.onMessageReceived(msg);
    if (msg.getNotification() != null) {
        Intent activityIntent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, activityIntent, PendingIntent.FLAG_ONE_SHOT);

        Notification note = new NotificationCompat.Builder(this, "channel_id")
                .setSmallIcon(R.mipmap.icon)
                .setContentTitle(msg.getNotification().getTitle())
                .setContentText(msg.getNotification().getBody())
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setAutoCancel(true)
                .setContentIntent(contentIntent)
                .setSound(SettingsHandler.getRingtoneUri(this))
                .setVibrate(SettingsHandler.shouldVibrateOnPush ? new long[] {500, 500, 500, 500, 500} : new long[] {0, 0, 0, 0, 0})
                .build();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //create notification channels
        }
        NotificationManagerCompat manager = NotificationManagerCompat.from(this);
        manager.notify(1, note);
    }
}

但是,当我发送通知时,总是播放默认声音,所以我开始问自己,我的思维方式是否有错误。任何方式如何正确地做到这一点?提前致谢。

【问题讨论】:

    标签: android firebase firebase-cloud-messaging android-notifications


    【解决方案1】:

    试试这个:
    您可以使用以下代码选择铃声:

    selsound_button.setOnClickListener(new OnClickListener()
        {   
            public void onClick(View arg0)
            {
                Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select ringtone for notifications:");
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentUri);
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,RingtoneManager.TYPE_NOTIFICATION);
        startActivityForResult( intent, 999);  
            }
        }); 
    

    然后您需要在 onActivityResult 方法中处理 currentUri 并将其存储在 sharedPreferences 中以供将来使用。

    实际工作在这里:

     @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == 999){
                if (data != null) {
                    currentUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
                }
                if (Settings.System.canWrite(this)){
                    RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION, currentUri);
                }else {
                    Intent settings = new Intent("android.settings.action.MANAGE_WRITE_SETTINGS");
                    startActivityForResult(settings, 124);
                }
            }
            if (requestCode == 124){
                if (resultCode == Activity.RESULT_OK){
                    RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION, currentUri);
                }
            }
        }
    

    现在从存储的 sharedPreferences 中获取 uri 并在通知中使用:

     notification.setSound(currentUri);
            notification.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }));
    

    注意:您需要拥有此任务的 WRITE_SETTINGS 权限。

    【讨论】:

    • 这会使用我可以通过RingtoneManager.ACTION_RINGTONE_PICKER 选择的铃声吗?这是用户可以在我的应用中选择铃声的方式。
    • @procra 我已经编辑了答案,这种方法有效,如果有任何疑问,请告诉我。 :)
    • 这正是我已经这样做的方式。然而,声音并没有真正设置好。也许我的 Uri 的框架无效。它看起来像 "content://media/internal/audio/media/31",但对我来说似乎是正确的。
    • @procra 最后我能够解决这个问题,编辑的答案肯定会起作用,剩下的工作是将 currentUri 存储在 sharedPreferences 中。希望这对你也有用。 :)
    【解决方案2】:

    创建资源文件夹(目录res)将其命名为raw并将文件(声音文件名.mp3)放入其中,然后使用以下代码自定义声音

    Notification note;
    .....
    ......
    note.sound = Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.filename);//file name you want to play
    

    奥利奥及更高版本的SKD需要放入通知频道

    Uri sounduri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.filename); //file name you want to play
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
            NotificationChannel Channel = new NotificationChannel("CHANNEL_ID","CHANNEL NAME", NotificationManager.IMPORTANCE_DEFAULT)
            AudioAttributes attributes;
            .... 
            ........
            Channel.setSound(sounduri, attributes); //set the sound
    
    
            if (notificationManager != null){
                notificationManager.createNotificationChannel(Channel);}
        }
    

    使用 MediaPlayer 类播放通知声音

    MediaPlayer sound = MediaPlayer.create(contex, R.raw.filename);
    sound.start();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多