I want to access my systems ringtones in flutter

Issue

Is there any way to get all the Ringtones of the phone using flutter, and set the chosen one as the default ringtone of my app?

thanks in advance

Solution

I managed to get it done using native code

  1. First you would create those things on the Flutter side.

    
    // here where your ringtones will be stored
    List<Object?> result = ['Andromeda'];
    
    // this is the channel that links flutter with native code
    static const channel = MethodChannel('com.example.pomo_app/mychannel');
    
    // this method waits for results from the native code 
    Future<void> getRingtones() async {
        try {
          result = await channel.invokeMethod('getAllRingtones');
        } on PlatformException catch (ex) {
          print('Exception: $ex.message');
        }
      }
    
    
  2. Know you need to implement the native code. Go to MainActivity.kt

    // add the name of the channel that we made in flutter code
    private val channel = "com.example.pomo_app/mychannel"
    
    // add this method to handle the calls from flutter
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channel)
      .setMethodCallHandler { call, result ->
                when (call.method) {
                    "getAllRingtones" -> {
                        result.success(getAllRingtones(this))
                    }
    
    
    
    // this function will return all the ringtones names as a list
    private fun getAllRingtones(context: Context): List<String> {
    
      val manager = RingtoneManager(context)
      manager.setType(RingtoneManager.TYPE_RINGTONE)
    
      val cursor: Cursor = manager.cursor
    
      val list: MutableList<String> = mutableListOf()
      while (cursor.moveToNext()) {
        val notificationTitle: String = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX)
        list.add(notificationTitle)
      }
      return list
    }
    

that’s it I hope this is helpful. any questions let me know.

Answered By – zaynOm

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *