I want to change the preferences for information alert only in my app without touching the system preferences to have a own signal or ringtone sound for messages.
In the example will change the system sound.
A datastore methode would be even better.
package com.bom.myappsettingsxsub
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.media.MediaPlayer
import android.media.Ringtone
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.preference.*
import ModelMain
import android.widget.EditText
import java.util.prefs.Preferences
private lateinit var viewModel:ModelMain
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_activity)
if (savedInstanceState == null) {
supportFragmentManager
.beginTransaction()
.replace(R.id.settings, SettingsFragment())
.commit()
}
val context: Context = MainActivity.applicationContext() // good idea
//val packageName : String = this.packageName
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
class SettingsFragment : PreferenceFragmentCompat(),
SharedPreferences.OnSharedPreferenceChangeListener {
var prefRingtone : Preference? = null
var ringtone : Ringtone? = null
var prefUsername : Preference? = null
var prefSyncEmail : SwitchPreferenceCompat? = null
lateinit var sharedPreferences: SharedPreferences
private var username = ""
// Todo add all contents
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
viewModel = ViewModelProvider(requireActivity()).get(ModelMain::class.java)
//ringtone = defaultRingtone
prefRingtone = findPreference(KEY_RINGTONE_PREFERENCE)
prefUsername = findPreference(KEY_SIGNATURE)
prefSyncEmail = findPreference(KEY_SYNC_EMAIL)
loadDataFromPreferences()
// set InputType
// SummeryPrvider
prefUsername?.summaryProvider = EditTextPreference.SimpleSummaryProvider.getInstance()
//val packageName1 : String = Context.getContext()
// wieder eingauben mit if openAndroidPermissionsMenu() // DONT DELETE !!! (it works fine)
// Extension function to get a media player to play default ringtone
//prefRingtone.setSummary(ringtone.getTitle(context))
//prefRingtone.setSummary(prefRingtone.)
fun defaultRingtonePlayer(): MediaPlayer {
return MediaPlayer.create(activity, Settings.System.DEFAULT_RINGTONE_URI)
}
val chgRing = preferenceManager.findPreference<Preference>(MainActivity.KEY_RINGTONE_PREFERENCE)
if (chgRing != null) {
chgRing.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { preference, newValue ->
Log.d(ContentValues.TAG, "(BOM) chgRing.onPreferenceChangeListener:SettingsFragment")
true
}
}
preferenceManager.findPreference<Preference>(KEY_RINGTONE_PREFERENCE)?.let {
it.setOnPreferenceChangeListener { preference, newValue -> true
}
Log.d(ContentValues.TAG, "(BOM) onCreate(SettingsFragment:PreferenceManager.findPreference):SettingsFragment")
true
}
checkSystemWritePermission()
}
// 2021-11-20
private fun loadDataFromPreferences()
{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
//val Preferences prefd = PreferenceManager. ???
username = sharedPreferences.getString(KEY_SIGNATURE, "")!!
}
override fun onSharedPreferenceChanged(
sharedPreferences: SharedPreferences?,
key: String?
) {
val x = 1
TODO("Not yet implemented")
if (key.equals(KEY_SIGNATURE)) {
viewModel.setLiveUserNameValue(sharedPreferences.toString())
}
}
override fun onPreferenceTreeClick(preference: Preference): Boolean {
return if (preference.key.equals(KEY_RINGTONE_PREFERENCE)) {
val currentRingtone: Uri = RingtoneManager.getActualDefaultRingtoneUri(
activity,
RingtoneManager.TYPE_RINGTONE
)
val intentRingTone = Intent(RingtoneManager.ACTION_RINGTONE_PICKER)
Log.d(TAG, "onPreferenceTreeClick")
intentRingTone.putExtra(
RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,
currentRingtone
)
intentRingTone.putExtra(
RingtoneManager.EXTRA_RINGTONE_TYPE,
RingtoneManager.TYPE_RINGTONE
)
intentRingTone.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)
intentRingTone.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true)
startActivityForResult(intentRingTone, REQUEST_RINGTONE)
true
} else {
super.onPreferenceTreeClick(preference)
true
}
}
companion object {
val DELETE_LIMIT = "pref_key_delete_limit"
val LIST = "pref_key_list"
val RINGTONE = "pref_notification_ringtone"
val REQUEST_USERNAME = 998
val REQUEST_RINGTONE = 999
val KEY_RINGTONE_PREFERENCE = "pref_key_notification_ringtone"
val KEY_SIGNATURE= "pref_key_signature"
val KEY_SYNC_EMAIL= "pref_key_syncemail"
private val TAG = this::class.java.name
private fun bindPreferenceSummaryToValue(preference: Preference) {
preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener
val onPreferenceChange =
sBindPreferenceSummaryToValueListener.onPreferenceChange(
preference,
PreferenceManager
.getDefaultSharedPreferences(preference.context)
//.getString(preference.key, "")
)
}
private val sBindPreferenceSummaryToValueListener =
Preference.OnPreferenceChangeListener { preference, newValue ->
val stringValue = newValue.toString()
Log.d(TAG, "(BOM) sBindPreference Param:" + stringValue)
if (preference is ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
val index = preference.findIndexOfValue(stringValue)
// Set the summary to reflect the new value.
preference.setSummary(
if (index >= 0)
preference.entries[index]
else
null
)
} else if (preference is Preference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary("Silent")
} else {
val ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue)
)
if (ringtone == null) {
// Clear the summary if there was a lookup error.
//preference.setSummary(androidx.preference.R.string.pref_sum_ringtone_silent)
} else {
// Set the summary to reflect the new ringtone display
// name.
val name = ringtone.getTitle(preference.getContext())
preference.setSummary(name)
}
}
} else if (preference is EditTextPreference) {
if (preference.getKey() == KEY_SIGNATURE) {
// update the changed gallery name to summary filed
preference.summary = stringValue
preference.setSummary(stringValue)
}
} else {
preference.summary = stringValue
}
true
}
}
override fun onDestroy() {
super.onDestroy()
androidx.preference.PreferenceManager.getDefaultSharedPreferences(context)
.unregisterOnSharedPreferenceChangeListener(this)
}
// Extension property to get default ringtone
val defaultRingtone: Ringtone
get() {
val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
return RingtoneManager.getRingtone(context, uri)
}
private fun openAndroidPermissionsMenu() {
val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
intent.data = Uri.parse("package:" + (getActivity()?.getPackageName() ?: String))
startActivity(intent)
}
private fun checkSystemWritePermission(): Boolean {
var retVal = true
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
retVal = Settings.System.canWrite(context)
//Log.d(PreferenceFragmentCompat.TAG, "Can Write Settings: $retVal")
if (retVal) {
Toast.makeText(context, "Write allowed :-)", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(context, "Write not allowed :-(", Toast.LENGTH_LONG).show()
/* val fm: FragmentManager? = fragmentManager
val dialogFragment = PopupWritePermission()
dialogFragment.show(fm, getString(R.string.popup_writesettings_title))*/
openAndroidPermissionsMenu()
}
}
return retVal
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Log.d(TAG, "onActivityResult")
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_RINGTONE && resultCode == Activity.RESULT_OK) {
val uri = data!!.getParcelableExtra<Uri>(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
Log.d(TAG, "[SET] Uri path Ringtone Var uri="+(uri))
val ringtone = RingtoneManager.getRingtone(context, uri)
val ringtoneName = ringtone.getTitle(context).toString()
viewModel.setLiveRingtoneNameValue(ringtoneName)
viewModel.setLiveRingtoneValue(ringtone)
prefRingtone?.setSummary(ringtoneName)
// 2022-03-27 RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, uri)
// Dont set !!!
}
if (requestCode == REQUEST_USERNAME && resultCode == Activity.RESULT_OK) {
viewModel.setLiveUserNameValue(data.toString())
}
}
private fun initLiveDataObserver()
{
viewModel.currentUserName.observe(viewLifecycleOwner, Observer { value ->
prefUsername?.summary
})
viewModel.currentRingtoneName.observe(viewLifecycleOwner, Observer {value ->
prefRingtone?.summary
})
}
}
}
class MySharedPrefChangeListener : SharedPreferences.OnSharedPreferenceChangeListener {
/**
* Called when a shared preference is changed, added, or removed.
*/
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (sharedPreferences == null)
return
if (sharedPreferences.contains(key)) {
// action to perform
var x = 4
}
//get().updateUI()
}
}