Перенаправить пользователя в раздел уведомлений приложения вместо использования RingtonePreference на Android Oreo - PullRequest
0 голосов
/ 19 апреля 2019

У меня есть простое приложение с разделом, где пользователь должен иметь возможность обновлять звук для входящих push-уведомлений.Начиная с Android Oreo, уведомления должны использовать канал уведомлений, для которого звук не может быть обновлен программно, поэтому это может сделать только пользователь в области «Уведомления приложения».

Поэтому я решил разрешитьпользователи обновляют звук с помощью функции RingtonePreference (для версий Android

User changes notification App Notification screen Ringtone Preference screen

Вот код, который выполняет перенаправление на уведомления приложений в зависимости от версии ОС:

public static class NotificationPreferenceFragment extends PreferenceFragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_notification);
            setHasOptionsMenu(true);

            bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
        }

        @Override
        public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                if (preference.getKey().equals("notifications_new_message_ringtone")) {
                    Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
                            .putExtra(Settings.EXTRA_APP_PACKAGE, preference.getContext().getPackageName())
                            .putExtra(Settings.EXTRA_CHANNEL_ID, CHANNEL_ID);
                    preference.getContext().startActivity(intent);
                    return true;
                }

            return false;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
public class SettingsActivity extends AppCompatPreferenceActivity {

    private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String stringValue = value.toString();

            if (preference instanceof ListPreference) {

                ListPreference listPreference = (ListPreference) preference;
                int index = listPreference.findIndexOfValue(stringValue);

                // Set the summary to reflect the new value.
                preference.setSummary(
                        index >= 0
                                ? listPreference.getEntries()[index]
                                : null);

            } else if (preference instanceof RingtonePreference) {

                if (TextUtils.isEmpty(stringValue)) {
                    // Empty values correspond to 'silent' (no ringtone).
                    preference.setSummary(R.string.pref_ringtone_silent);

                } else {
                    Ringtone ringtone = RingtoneManager.getRingtone(
                            preference.getContext(), Uri.parse(stringValue));

                    if (ringtone == null) {
                        // Clear the summary if there was a lookup error.
                        preference.setSummary(null);
                    } else {
                        // Set the summary to reflect the new ringtone display
                        // name.
                        String name = ringtone.getTitle(preference.getContext());
                        preference.setSummary(name);
                    }
                }

            } else if (preference instanceof SwitchPreference) {
                android.app.NotificationManager notificationManager = (android.app.NotificationManager) preference.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancel(1);
            } else {

                preference.setSummary(stringValue);
            }
            return true;
        }
    };
}

Вопросы: 1. Можно ли встроить панель инструментов с кнопкой «Назад» на экран уведомлений Android?(чтобы позволить пользователю легко вернуться в основное приложение) (я полагаю, нет ..) 2. Как я могу обойти пользователя, когда он видит экран RingtonePreference при ручном нажатии кнопки возврата телефона?

Большое спасибо!

...