public void cargarfavoritos()
        {
            try
            {
                adaptadorcartas adap = new adaptadorcartas(favoritos, this);
                adap.ItemClick += (aa, aaa) =>
                {
                    RunOnUiThread(() =>
                    {
                        var elemento   = favoritos[aaa.Position];
                        Intent intento = new Intent(this, typeof(customdialogact));

                        intento.PutExtra("url", elemento.Link);
                        intento.PutExtra("titulo", elemento.Name);
                        intento.PutExtra("imagen", "http://i.ytimg.com/vi/" + elemento.Link.Split('=')[1] + "/mqdefault.jpg");
                        StartActivity(intento);
                    });
                };
                adap.ItemLongClick += (aa, aaa) =>
                {
                    RunOnUiThread(() =>
                    {
                        var elemento = favoritos[aaa.Position];
                        new Android.App.AlertDialog.Builder(this)
                        .SetTitle("Advertencia")
                        .SetMessage("Desea eliminar este elemento de la lista de favoritos?")
                        .SetPositiveButton("Si", (aax, asd) =>
                        {
                            Diccfavoritos = PlaylistsHelper.AddToFavouriteList(this, Diccfavoritos, elemento);
                            favoritos     = Diccfavoritos.Values.ToList();
                            favoritos.Reverse();
                            cargarfavoritos();
                        })
                        .SetNegativeButton("No", (asdd, ffff) => { })
                        .Create()
                        .Show();
                    });
                };
                RunOnUiThread(() =>
                {
                    listafavoritos.SetAdapter(adap);
                    if (favoritos.Count > 0)
                    {
                        secciones[2].Visibility = ViewStates.Visible;
                        if (!SettingsHelper.HasKey("dialogofavoritos"))
                        {
                            RunOnUiThread(() =>
                            {
                                new Android.Support.V7.App.AlertDialog.Builder(this)
                                .SetTitle("Informacion")
                                .SetMessage("Al dejar presionado un elemento de favoritos usted podra eliminarlo de la lista")
                                .SetCancelable(false)
                                .SetPositiveButton("Entendido", (aa, fddggfd) => { })
                                .Create()
                                .Show();
                                SettingsHelper.SaveSetting("dialogofavoritos", "si");
                            });
                        }
                    }
                    else
                    {
                        secciones[2].Visibility = ViewStates.Gone;
                    }
                });
            }
            catch (Exception)
            {
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Configuraciones);

            ISharedPreferences       prefs      = Application.Context.GetSharedPreferences("Settings", FileCreationMode.Private);
            ISharedPreferencesEditor prefEditor = prefs.Edit();

            botonseleccionarcarpeta = FindViewById <Button>(Resource.Id.imageView1);
            localizacion            = FindViewById <TextView>(Resource.Id.textView3);
            //   botonguardar = FindViewById<ImageView>(Resource.Id.imageView2);
            var colormuestra = FindViewById <ImageView>(Resource.Id.imageView3);

            colormuestra.SetBackgroundColor(Color.ParseColor(SettingsHelper.GetSetting("color")));
            color            = SettingsHelper.GetSetting("color");
            reprodautomatica = SettingsHelper.GetSetting("automatica");
            var ll1             = FindViewById <LinearLayout>(Resource.Id.linearLayout3);
            var ll2             = FindViewById <LinearLayout>(Resource.Id.linearLayout4);
            var ll3             = FindViewById <LinearLayout>(Resource.Id.linearLayout5);
            var ll4             = FindViewById <LinearLayout>(Resource.Id.linearLayout7);
            var ll5             = FindViewById <LinearLayout>(Resource.Id.linearLayout23);
            var fondo           = FindViewById <ImageView>(Resource.Id.fondo1);
            var toggle1         = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.toggleButton1);
            var toggle2         = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.toggleButton2);
            var automatica      = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.automatico);
            var botonclearcache = FindViewById <LinearLayout>(Resource.Id.linearLayout8);

            calidades = FindViewById <Spinner>(Resource.Id.spinner1);
            var action = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.my_toolbar);

            //////////////////////////////////////coloreselector mappings

#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
            dialogoprogreso = new ProgressDialog(this);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
            ///////////////////////////////////////////////////////////

            ////////////////////////////////////////////////////////////////
            ///
            if (reprodautomatica == "si")
            {
                automatica.Checked = true;
            }
            else
            {
                automatica.Checked = false;
            }


            SetSupportActionBar(action);
            SupportActionBar.Title = "Preferencias";
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);

            var adapter = new  ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem);
            adapter.AddAll(new string[] { "Audio", "360p", "720p" }.ToList());
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            calidades.Adapter = adapter;

            color   = SettingsHelper.GetSetting("color");
            calidad = int.Parse(SettingsHelper.GetSetting("video"));
            switch (calidad)
            {
            case -1:
                calidades.SetSelection(0);
                break;

            case 360:
                calidades.SetSelection(1);
                break;

            case 720:
                calidades.SetSelection(2);
                break;
            }

            if (SettingsHelper.HasKey("abrirserver"))
            {
                abrirserver = SettingsHelper.GetSetting("abrirserver");
            }
            if (abrirserver == "no")
            {
                toggle2.Checked = false;
            }
            else
            {
                toggle2.Checked = true;
            }


            if (SettingsHelper.HasKey("ordenalfabeto"))
            {
                ordenalfabeto = SettingsHelper.GetSetting("ordenalfabeto");

                if (ordenalfabeto == "si")
                {
                    toggle1.Checked = true;
                }
                else
                {
                    toggle1.Checked = false;
                }
            }

            if (SettingsHelper.HasKey("rutadescarga"))
            {
                klk = prefs.GetString("rutadescarga", null);
            }
            else
            {
                if (Directory.Exists(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads"))
                {
                    klk = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads";
                    prefEditor.PutString("rutadescarga", klk);
                    prefEditor.Commit();
                }
                else
                {
                    Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads");
                    klk = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads";
                    prefEditor.PutString("rutadescarga", klk);
                    prefEditor.Commit();
                }
            }

            localizacion.Text = klk;

            fondo.SetImageBitmap(CreateBlurredImageoffline(this, 20, 0));
            ////////////////////////////////clicks////////////////////////////

            calidades.ItemSelected += (axx, ssd) => {
                switch (ssd.Position)
                {
                case 0:
                    calidad = -1;
                    break;

                case 1:
                    calidad = 360;
                    break;

                case 2:
                    calidad = 720;
                    break;
                }
            };
            automatica.Click += delegate
            {
                if (automatica.Checked)
                {
                    reprodautomatica = "si";
                    Toast.MakeText(this, "Si no hay mas elementos en cola se reproducira el primer elemento de las sugerencias", ToastLength.Long).Show();
                }
                else
                {
                    reprodautomatica = "no";
                    Toast.MakeText(this, "Si no hay mas elementos en cola no se ejecutara ninguna accion", ToastLength.Long).Show();
                }
            };
            toggle2.Click += delegate
            {
                if (toggle2.Checked)
                {
                    new Thread(() =>
                    {
                        if (PlaylistsHelper.HasMediaElements)
                        {
                            if (File.Exists(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.gr3cache/version.gr3v"))
                            {
                                abrirserver = "si";

                                StartService(new Intent(this, typeof(serviciostreaming)));
                            }
                            else

                            {
                                AlertDialog dialogo = null;
                                RunOnUiThread(() => {
                                    var progresox           = new ProgressBar(this);
                                    progresox.Indeterminate = true;

                                    dialogo = new AlertDialog.Builder(this)
                                              .SetTitle("Buscando actualizaciones")
                                              .SetMessage("Por favor espere...")
                                              .SetCancelable(false)
                                              .SetView(progresox)
                                              .Show();
                                });
                                if (CheckInternetConnection())
                                {
                                    abrirserver        = "si";
                                    AlertDialog alerta = null;
                                    RunOnUiThread(() =>
                                    {
                                        dialogo.Dismiss();
                                        var progreso           = new ProgressBar(this);
                                        progreso.Indeterminate = true;

                                        alerta = new AlertDialog.Builder(this)
                                                 .SetTitle("Descargando archivos necesarios")
                                                 .SetMessage("Por favor espere...")
                                                 .SetCancelable(false)
                                                 .SetView(progreso)
                                                 .Show();
                                    });
                                    new Thread(() =>
                                    {
                                        WebClient cliente = new WebClient();
                                        var version       = cliente.DownloadString("https://raw.githubusercontent.com/Gr3gorywolf/Multitube.android/master/Updates/version.gr3v");
                                        using (var file = File.CreateText(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.gr3cache/version.gr3v")) {
                                            file.Write(version);
                                            file.Close();
                                        }
                                        MultitubeWebHelper.UpdateMultitubeWeb(version);
                                        RunOnUiThread(() =>
                                        {
                                            alerta.Dismiss();
                                            StartService(new Intent(this, typeof(serviciostreaming)));
                                            new AlertDialog.Builder(this)
                                            .SetTitle("Informacion")
                                            .SetMessage("El servidor de streaming le permitirara reproducir su contenido previamente descargado desde cualquier navegador de cualquier dispositivo conectado a su misma red. Puede consultar el estado de este en la barra de notificaciones")
                                            .SetPositiveButton("Entendido!", (aa, fff) => { })
                                            .Create()
                                            .Show();
                                        });
                                    }).Start();
                                }
                                else
                                {
                                    RunOnUiThread(() =>
                                    {
                                        dialogo.Dismiss();
                                        Toast.MakeText(this, "Debe tener una conexion a internet para abrir el servicio por primera vez", ToastLength.Long).Show();
                                        toggle2.Checked = false;
                                    });
                                }
                            }
                        }
                        else
                        {
                            RunOnUiThread(() =>
                            {
                                toggle2.Checked = false;
                                Toast.MakeText(this, "Debe tener almenos 1 elemento descargado", ToastLength.Long).Show();
                            });
                        }
                    }).Start();
                }
                else
                {
                    if (serviciostreaming.gettearinstancia() != null)
                    {
                        StopService(new Intent(this, typeof(serviciostreaming)));
                    }
                    toggle2.Checked = false;
                    abrirserver     = "no";
                }
            };
            botonclearcache.Click += delegate
            {
                AlertDialog.Builder ad = new AlertDialog.Builder(this);
                ad.SetCancelable(false);
                ad.SetTitle("Advertencia");
                ad.SetIcon(Resource.Drawable.alert);
                ad.SetMessage("Limpiar el cache puede provocar cierta realentizacion a la hora de entrar al reproductor offline y tambien volvera a descargar los datos por lo cual necesitara internet ¿¿quiere borrar cache??");
                ad.SetNegativeButton("No", no);
                ad.SetPositiveButton("Si", si);
                ad.Create();
                ad.Show();
            };
            toggle1.Click += delegate
            {
                if (toggle1.Checked == true)
                {
                    ordenalfabeto = "si";
                    Toast.MakeText(this, "Los elementos se organizaran alfabeticamente", ToastLength.Long).Show();
                }
                else
                {
                    ordenalfabeto = "no";
                    Toast.MakeText(this, "Los elementos se por fecha de descarga", ToastLength.Long).Show();
                }
            };
            botonseleccionarcarpeta.Click += async delegate
            {
                SimpleFileDialog sfd = new SimpleFileDialog(this, SimpleFileDialog.FileSelectionMode.FolderChooseRoot);
                klk = await sfd.GetFileOrDirectoryAsync(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath);

                if (probarpath(klk))
                {
                    pathvalido = true;

                    localizacion.Text = klk;
                }
                else
                {
                    Toast.MakeText(this, "Ruta invalida seleccione otra", ToastLength.Short).Show();
                    klk        = localizacion.Text;
                    pathvalido = false;
                }
            };
        }
        public void descargar(string path, string archivo, string titulo, string link)
        {
            WebClient cliente2 = new WebClient();

            cliente2.DownloadFileAsync(new Uri("https://i.ytimg.com/vi/" + link.Split('=')[1] + "/mqdefault.jpg"), Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + link.Split('=')[1]);
            //new
            if (titulo.Trim().Length > 45)
            {
                titulo = titulo.Remove(45);
            }
            tituloo = titulo;


            var manige = DownloadManager.FromContext(this);
            var requ   = new DownloadManager.Request(Android.Net.Uri.Parse(archivo));

            requ.SetDescription("Espere por favor");
            requ.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
            requ.SetTitle(tituloo);
            var destino = Android.Net.Uri.FromFile(new Java.IO.File(path));

            if (SettingsHelper.GetSetting("rutadescarga") == Android.OS.Environment.DirectoryDownloads)
            {
                requ.SetDestinationInExternalPublicDir(SettingsHelper.GetSetting("rutadescarga"), Path.GetFileName(path));
            }
            else
            {
                requ.SetDestinationUri(destino);
            }
            requ.AllowScanningByMediaScanner();

            requ.SetVisibleInDownloadsUi(true);



            manige.Enqueue(requ);

            if (Path.GetFileName(path).EndsWith(".mp3"))
            {
                ////////////////si es mp3
                string datosviejos = "";
                if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d"))
                {
                    datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                }
                else
                {
                    var asss = File.Create(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                    asss.Close();
                }
                if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
                {
                    Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
                }

                if (!datosviejos.Contains(link.Split('=')[1]))
                {
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                    aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
                    aafff.Close();
                }
                else
                {
                    var datosparsed   = PlaylistsHelper.GetMedia(Constants.CachePath + "/downloaded.gr3d");
                    var videoid       = link.Split('=')[1];
                    int indexelemento = datosparsed.FindIndex(ax => ax.Link.Contains(videoid));
                    datosparsed[indexelemento].Path = path;
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                    aafff.Write(PlaylistsHelper.SerializeMedia(datosparsed));
                    aafff.Close();
                }
            }
            //////////////////////////////////////////////si es mp4
            else
            {
                string datosviejos = "";
                if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2"))
                {
                    datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                }
                else
                {
                    var asss = File.Create(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                    asss.Close();
                }
                if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
                {
                    Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
                }

                if (!datosviejos.Contains(link.Split('=')[1]))
                {
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                    aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
                    aafff.Close();
                }
                else
                {
                    var datosparsed   = PlaylistsHelper.GetMedia(Constants.CachePath + "/downloaded.gr3d2");
                    var videoid       = link.Split('=')[1];
                    int indexelemento = datosparsed.FindIndex(ax => ax.Link.Contains(videoid));
                    datosparsed[indexelemento].Path = path;
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                    aafff.Write(PlaylistsHelper.SerializeMedia(datosparsed));
                    aafff.Close();
                }
                MultiHelper.ExecuteGarbageCollection();
            }



            /*
             * Random brandom = new Random();
             * WebClient cliente2= new WebClient();
             * cliente2.DownloadFileAsync(new Uri("https://i.ytimg.com/vi/" + link.Split('=')[1] + "/mqdefault.jpg"), Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + link.Split('=')[1]);
             * int randum = brandom.Next(2000, 50000) + brandom.Next(2000, 50000);
             * random = randum;
             * try {
             *  NotificationManager notificationManager =
             *   GetSystemService(Context.NotificationService) as NotificationManager;
             *  if (titulo.Trim().Length > 30)
             *  {
             *      titulo = titulo.Remove(30);
             *  }
             *  tituloo = titulo;
             *  var builder = new Notification.Builder(ApplicationContext);
             *  builder.SetContentTitle("Descargando " + titulo + "...");
             *  builder.SetContentText("Espere por favor");
             *
             *  builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *
             *
             *
             *  WebClient cliente = new WebClient();
             *
             * byte[] losbits = null;
             *  cliente.DownloadProgressChanged += (aasd, asddd) =>
             *  {
             *
             *      builder.SetContentTitle("Descargando "+titulo+"...");
             *      builder.SetContentText("Espere por favor");
             *      builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *      builder.SetProgress(100, asddd.ProgressPercentage, false);
             *      notificationManager.Notify(randum, builder.Build());
             *
             *  };
             * cliente.DownloadDataCompleted += (aa, aaa) =>
             * {
             *
             *  //  Intent intentss = new Intent(this,typeof(actividadacciones));
             *  //  intentss.PutExtra("prro", path);
             *  try {
             *  var selectedUri = Android.Net.Uri.Parse( prefs.GetString("rutadescarga",null)+ "/");
             *
             *  Intent intentssdd = new Intent(this,typeof(actividadadinfooffline));
             *  intentssdd.PutExtra("nombre", Path.GetFileName(path));
             *  intentssdd.PutExtra("link", link);
             *  intentssdd.PutExtra("path", path);
             *
             *
             *
             *
             *
             *  PendingIntent intentosd = PendingIntent.GetActivity(this, brandom.Next(2000, 50000) + brandom.Next(2000, 50000), intentssdd, PendingIntentFlags.UpdateCurrent);
             *
             *
             *  builder.SetContentTitle("Descarga completada de: "+titulo);
             *  builder.SetContentText("Toque para abrir");
             *  builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *  builder.SetContentIntent(intentosd);
             *      builder.SetOngoing(false);
             *      notificationManager.Notify(randum, builder.Build());
             *
             *  losbits = aaa.Result;
             *  var a = File.Create(path);
             *  a.Write(losbits, 0, losbits.Length);
             *  a.Close();
             *  string datosviejos = "";
             *  link = link.Replace('²', ' ');
             *  link= link.Replace('¤', ' ');
             *  path =path.Replace('²', ' ');
             *  path=path.Replace('¤', ' ');
             *
             *
             *  if (Path.GetFileName(path).EndsWith(".mp3")) {
             *  ///////////////////////////si es mp3
             *
             *  if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d"))
             *  {
             *     datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
             *  }
             *  if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
             *  {
             *      Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
             *  }
             *
             *  if(!datosviejos.Contains(Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤"))
             *  {
             *      var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
             *      aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
             *      aafff.Close();
             *
             *  }
             *
             *
             *  }
             *  //////////////////////////////////////////////si es mp4
             *  else
             *  {
             *      if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2"))
             *      {
             *          datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
             *      }
             *      if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
             *      {
             *          Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
             *      }
             *
             *      if (!datosviejos.Contains(Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤"))
             *      {
             *          var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
             *          aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
             *          aafff.Close();
             *
             *      }
             *          clasesettings.recogerbasura();
             *  }
             *      completada = true;
             *  }
             *  catch (Exception)
             *  {
             *      clasesettings.recogerbasura();
             *      Toast.MakeText(this, "ha ocurrido un error al descargar intente de nuevo", ToastLength.Long).Show();
             *     // StopForeground(false);
             *  }
             *
             * };
             *
             *  cliente.DownloadData(new Uri(archivo));
             * }
             * catch (Exception)
             * {
             *  NotificationManager notificationManager =
             *  GetSystemService(Context.NotificationService) as NotificationManager;
             *  var builder = new Notification.Builder(ApplicationContext);
             *  builder.SetContentTitle("ERROR AL DESCARGAR: " + titulo);
             *  builder.SetContentText("Intente de nuevo");
             *  builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *  builder.SetOngoing(false);
             *  notificationManager.Notify(randum, builder.Build());
             *  clasesettings.recogerbasura();
             *
             * }
             */
        }
        public void reproducir(string downloadurl, bool desdecache)
        {
            // musicaplayer.SetDataSource(downloadurl);
            if (playeroffline.gettearinstancia() != null)
            {
                try
                {
                    musicaplayer.Release();


                    musicaplayer = new MediaPlayer();

#pragma warning disable 414
                    if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.N)
                    {
                        musicaplayer.SetAudioAttributes(new AudioAttributes.Builder()
                                                        .SetUsage(AudioUsageKind.Media)
                                                        .SetContentType(AudioContentType.Music)
                                                        .Build());
                    }
                    else
                    {
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                        musicaplayer.SetAudioStreamType(Android.Media.Stream.Music);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
                    }

#pragma warning restore 414
                    musicaplayer.SetWakeMode(this, WakeLockFlags.Partial);
#pragma warning disable 414
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                    var focusResult = audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
#pragma warning restore 414
                    if (focusResult != AudioFocusRequest.Granted)
                    {
                        //could not get audio focus
                        Console.WriteLine("Could not get audio focus");
                    }


                    musicaplayer.Prepared += delegate
                    {
                        musicaplayer.Start();
                        if (this.desdecache)
                        {
                            musicaplayer.Pause();
                        }
                        if (playeroffline.gettearinstancia() != null)
                        {
                            if (playeroffline.gettearinstancia().video.Visibility == ViewStates.Visible)
                            {
                                musicaplayer.SetDisplay(null);
                                musicaplayer.SetDisplay(playeroffline.gettearinstancia().holder);
                            }

                            if (SettingsHelper.HasKey("posactual") && this.desdecache)
                            {
                                var posicion = 0;
                                try
                                {
                                    posicion = int.Parse(SettingsHelper.GetSetting("posactual"));
                                    musicaplayer.SeekTo(posicion);
                                }
                                catch (Exception) { }
                            }
                        }
                    };
                    musicaplayer.Completion += delegate
                    {
                        playeroffline.gettearinstancia().RunOnUiThread(() =>
                        {
                            playeroffline.gettearinstancia().RunOnUiThread(() =>
                            {
                                playeroffline.gettearinstancia().siguiente.PerformClick();
                            });
                        });
                    };

                    musicaplayer.SetDataSource(this, Android.Net.Uri.Parse(downloadurl.Trim()));
                    mostrarnotificacion();
                    musicaplayer.PrepareAsync();
                }
                catch (Exception)
                {
                    //if()

                    playeroffline.gettearinstancia().RunOnUiThread(() =>
                    {
                        Toast.MakeText(playeroffline.gettearinstancia(), "Error al reproducir", ToastLength.Long).Show();
                    });
                }
            }
            else
            {
                musicaplayer.Reset();
                StopSelf();
            }
        }