我可以设置自定义的铃声和振动模式以作为Firebase通知吗?

时间:2018-12-03 16:20:42

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

最近,我开始编码我的第一个包含Firebase Cloud Messaging的android项目。我使用的是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收到通知时,我想设置用户可以使用上述方法设置的声音和振动模式。

要获取此信息,我会覆盖onMessageReceived中扩展的MyFirebaseMessagingService方法-谁曾期望这样做-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);
    }
}

但是,当我发送通知时,始终会播放默认声音,所以我开始问自己,我的思维方式是否有误。任何方法如何正确执行?谢谢。

2 个答案:

答案 0 :(得分: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权限才能执行此任务。

答案 1 :(得分:0)

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

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

对于 Oreo和更高版本的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);}
    }

OR 使用MediaPlayer类播放声音以进行通知

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