Как составить список звуков уведомлений в android? - PullRequest
0 голосов
/ 12 апреля 2020

Я хочу, чтобы пользователи настраивали свое приложение, выбирая звук уведомления, но я не знаю, как составить список звука и как установить их в качестве звука уведомления. Я искал и пробовал разными способами, но это не сработало, пожалуйста, помогите мне!

Это мой код для отображения уведомлений:

NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channelID)
                .setSmallIcon(R.drawable.logo) /// Set notification's icon
                .setSound(uri) /// Set sound
                .setAutoCancel(true) /// Allow sound to auto cancel
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}) /// Set sound vibration
                .setOnlyAlertOnce(true) /// Only alert Once
                .setContentIntent(pendingIntent) /// Set intent it will show when click notification
                .setContent(getCustomDesign(title, message)); /// Set the design of notification

        /// Manage notification
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        /// Check if android version is Oreo or upper to show notification via NotificationChannel
        /// For each channel, you can set the and auditory behavior that is applied to all notifications in that channel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            /// Set channel's ID, name, and importance
            NotificationChannel notificationChannel = new NotificationChannel(channelID, "DEMO", notificationManager.IMPORTANCE_HIGH);

            /// Set sound for channel
            notificationChannel.setSound(uri, null);

            /// Create channel
            notificationManager.createNotificationChannel(notificationChannel);
        }

        /// Show the notification
        notificationManager.notify(0, builder.build());

Я пытался создать RingTone Средство выбора:

btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
                intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
                intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select notification tone");
                intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
                startActivityForResult(intent, 5);
            }
        });

и onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (resultCode == NotificationActivity.RESULT_OK && requestCode == 5) {
            Uri uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);

            if (uri != null) {
                //NotificationActivity.this.chosenRingtone = uri.toString();
                RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION, uri);
            } else {
                //this.chosenRingtone = null;
            }
        }
    }

Но Logcat сообщил, что моему проекту не предоставлено это разрешение: android .permission.WRITE_SETTINGS.

1 Ответ

0 голосов
/ 12 апреля 2020

Попробуйте выполнить это для выбора средства выбора уведомлений: -

    private class ToneItem {

    private String title = null;
    private String uri = null;

    private ToneItem(String title, String uri) {
        this.title = title;
        this.uri = uri;
    }

    public String getTitle() {
        return title;
    }

    public String getUri() {
        return uri;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

}

     private ArrayList<ToneItem> listRingTones() {
    RingtoneManager manager = new RingtoneManager(this);
    manager.setType(RingtoneManager.TYPE_NOTIFICATION);

    ArrayList<ToneItem> toneItems = new ArrayList<>();
    toneItems.add(new ToneItem("None", "/"));
    Cursor cursor = manager.getCursor();
    if (cursor != null) {
        while (cursor.moveToNext()) {
            String id = cursor.getString(RingtoneManager.ID_COLUMN_INDEX);
            String title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
            String uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);

            ToneItem toneItem = new ToneItem(title, uri + "/" + id);
            toneItems.add(toneItem);
        }
    } else {
        //nothing
    }

    return toneItems;
}
private void showNotificationToneDialog( String title) {
    final ArrayList<ToneItem> toneItems = listRingTones();

    String[] options = new String[toneItems.size()];
    for (int index = 0; index < toneItems.size(); index++) {
        options[index] = toneItems.get(index).title;
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
    builder.setTitle(title)

            .setItems(options, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    ToneItem selectedTone = toneItems.get(which);
        //HERE SAVE THE SELECTED TONE URI(selectedTone.uri) IN SHARED PREFERENCES
                }
            });

    builder.create().show();
}

И для установки звука уведомлений получите сохраненный URI из предпочтения и установите его для построителя уведомлений

     Uri uri = Uri.parse(//Get the saved uri from prefernce);
     mBuilder.setSound(uri);
...