public string RetrivePathForPDF(string name) { string _path = ""; _path = Path.Combine(_newPath, name); Java.IO.File f = new Java.IO.File(_path); Uri uri; if (Build.VERSION.SdkInt >= BuildVersionCodes.N) { uri = Uri.Parse("content://" + _path); } else { Java.IO.File file = new Java.IO.File(_path); file.SetReadable(true); //Android.Net.Uri uri = Android.Net.Uri.Parse("file://" + filePath); uri = Uri.FromFile(file); } var uri1 = FileProvider.GetUriForFile(MainActivity.MainActivityInstance.ApplicationContext, MainActivity.MainActivityInstance.ApplicationContext.PackageName + ".provider", f); return(uri1.Path); }
public static void GoToFrPlayStore(Context context) { var intent = new Intent(Intent.ActionView); intent.SetData(Uri.Parse("market://details?id=com.fanreact.app")); context.StartActivity(intent); }
private bool AttemptToHandleCustomUrlScheme(Android.Webkit.WebView view, string url) { if (url.StartsWith("mailto")) { MailTo emailData = MailTo.Parse(url); var email = new Intent(Intent.ActionSendto); email.SetData(Uri.Parse("mailto:")); email.PutExtra(Intent.ExtraEmail, new[] { emailData.To }); email.PutExtra(Intent.ExtraSubject, emailData.Subject); email.PutExtra(Intent.ExtraCc, emailData.Cc); email.PutExtra(Intent.ExtraText, emailData.Body); if (email.ResolveActivity(Forms.Context.PackageManager) != null) { Forms.Context.StartActivity(email); } return(true); } if (url.StartsWith("http")) { var webPage = new Intent(Intent.ActionView, Uri.Parse(url)); if (webPage.ResolveActivity(Forms.Context.PackageManager) != null) { Forms.Context.StartActivity(webPage); } return(true); } return(false); }
public async void PlaySong(QueueSong queue) { _appSettingsHelper.Write(PlayerConstants.CurrentTrack, queue.Id); if (_alreadyStarted) { _player.Reset(); } else { StartForeground(NotificationId, BuildNotification()); } _alreadyStarted = true; try { await _player.SetDataSourceAsync(ApplicationContext, Uri.Parse(queue.Song.AudioUrl)); MediaPlayerState = MediaPlayerState.Buffering; _player.PrepareAsync(); } catch (Exception e) { MediaPlayerState = MediaPlayerState.None; Log.Error("MUSIC SERVICE", "Player error", e); } }
/// <summary> /// Make the call /// </summary> /// <param name="phoneNumber">Phone number.</param> void MakeCall(string phoneNumber) { var uri = Uri.Parse($"tel:{phoneNumber}"); var callIntent = new Intent(Intent.ActionCall, uri); StartActivity(callIntent); }
protected override async void OnHandleIntent(Intent intent) { //UDP Receiver var listenPort = 15000; var receiver = new UdpSocketReceiver(); receiver.MessageReceived += (sender, args) => { //Daten und Senderadresse auswerten var from = String.Format("{0}:{1}", args.RemoteAddress, args.RemotePort); var data = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length); //Falls Link übermittelt if (string.IsNullOrEmpty(data) == false) { //Starte MainActivity (mit erhaltener URI) Intent i = new Intent(this, typeof(MainActivity)); i.SetData(Uri.Parse(data)); //i.AddFlags(ActivityFlags.NewTask); this.StartActivity(i); } }; //Abhören am UDP Port starten await receiver.StartListeningAsync(listenPort); }
static public void NotifyUpload(Context context, int id, bool replace, string tickerText, string title, string text, string imagePath, string thumbnailPath) { Settings settings = new Settings(context); Uri soundUri = settings.uploadSound != null?Uri.Parse(settings.uploadSound) : null; Intent intent = GetBaseIntent(context, imagePath); NotifyCommon(context, id, replace, tickerText, title, text, Resource.Drawable.TransferUp, intent, false, soundUri, settings.uploadVibration, Uri.Parse("file://" + thumbnailPath)); }
static public void NotifyDownload(Context context, int id, bool replace, string tickerText, string title, string text, Uri imageUri) { Settings settings = new Settings(context); Uri soundUri = settings.downloadSound != null?Uri.Parse(settings.downloadSound) : null; Intent intent = GetBaseIntent(context, ""); intent.SetDataAndType(imageUri, "image/*"); NotifyCommon(context, id, replace, tickerText, title, text, Resource.Drawable.TransferDown, intent, true, soundUri, settings.downloadVibration, imageUri); }
public void PlayAudio(string filepath) { _player.Stop(); _player.Reset(); if (FileExists(filepath)) { _player.SetDataSource(Application.Context, Uri.Parse(filepath)); _player.Prepare(); _player.Start(); } }
public void SendSms(string phoneNumber) { try { var context = Mvx.Resolve <IDroidService>().CurrentContext; var intent = new Intent(Intent.ActionView, Uri.Parse("sms:" + phoneNumber)); context.StartActivity(intent); } catch (Exception ex) { Log.Error("SendSms", ex.Message); } }
internal static AndroidUri GetShareableFileUri(FileBase file) { Java.IO.File sharedFile; if (FileProvider.IsFileInPublicLocation(file.FullPath)) { // we are sharing a file in a "shared/public" location sharedFile = new Java.IO.File(file.FullPath); } else { var rootDir = FileProvider.GetTemporaryDirectory(); // create a unique directory just in case there are multiple file with the same name var tmpDir = new Java.IO.File(rootDir, Guid.NewGuid().ToString("N")); tmpDir.Mkdirs(); tmpDir.DeleteOnExit(); // create the new temprary file var tmpFile = new Java.IO.File(tmpDir, file.FileName); tmpFile.DeleteOnExit(); var fileUri = AndroidUri.Parse(file.FullPath); if (fileUri.Scheme == "content") { using var stream = Application.Context.ContentResolver.OpenInputStream(fileUri); using var destStream = System.IO.File.Create(tmpFile.CanonicalPath); stream.CopyTo(destStream); } else { System.IO.File.Copy(file.FullPath, tmpFile.CanonicalPath); } sharedFile = tmpFile; } // create the uri, if N use file provider if (HasApiLevelN) { var providerAuthority = AppContext.PackageName + ".fileProvider"; return(FileProvider.GetUriForFile( AppContext.ApplicationContext, providerAuthority, sharedFile)); } // use the shared file path created return(AndroidUri.FromFile(sharedFile)); }
protected virtual void ShowFileFromLocalPath(string path, bool delete = false) { Java.IO.File f = new Java.IO.File(path); Uri uri; if (Build.VERSION.SdkInt >= BuildVersionCodes.N) { uri = Uri.Parse("content://" + path); } else { Java.IO.File file = new Java.IO.File(path); file.SetReadable(true); //Android.Net.Uri uri = Android.Net.Uri.Parse("file://" + filePath); uri = Uri.FromFile(file); } var uri1 = FileProvider.GetUriForFile(MainActivity.MainActivityInstance.ApplicationContext, MainActivity.MainActivityInstance.ApplicationContext.PackageName + ".provider", f); var t = uri1.Authority; Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType(uri1, GetMimeType(uri1, path)); intent.AddFlags(ActivityFlags.GrantReadUriPermission); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask); try { Application.Context.StartActivity(intent); } catch (ActivityNotFoundException e) { } catch (System.Exception) { throw; } finally { if (delete) { Task.Delay(2000); File.Delete(path); } } }
//@SuppressLint("MissingPermission") private void makeCall() { // If permission to call is granted if (CheckSelfPermission(Android.Manifest.Permission.CallPhone) == Permission.Granted) { // Create the Uri from phoneNumberInput Uri uri = Uri.Parse("tel:" + phoneNumberInput.ToString()); // Start call to the number in input StartActivity(new Intent(Intent.ActionCall, uri)); } else { // Request permission to call ActivityCompat.RequestPermissions(this, new string[] { Android.Manifest.Permission.CallPhone }, REQUEST_PERMISSION); } }
static Intent GetBaseIntent(Context context, string imagePath) { Intent intent; if (imagePath == null) { intent = new Intent(context, typeof(MainActivity)); } else { intent = new Intent(); intent.SetAction(Intent.ActionView); intent.SetDataAndType(Uri.Parse("file://" + imagePath), "image/*"); } return(intent); }
// PG사 호출 url 로드시 예외 처리용 함수 protected bool handleNotFoundPaymentScheme(String scheme) { //PG사에서 호출하는 url에 package정보가 없어 ActivityNotFoundException이 난 후 market 실행이 안되는 경우 if (PaymentScheme.ISP.Equals(scheme, StringComparison.OrdinalIgnoreCase)) { Uri uri = Uri.Parse("market://details?id=" + PaymentScheme.PACKAGE_ISP); context.StartActivity(new Intent(Intent.ActionView, uri)); return(true); } else if (PaymentScheme.BANKPAY.Equals(scheme, StringComparison.OrdinalIgnoreCase)) { Uri uri = Uri.Parse("market://details?id=" + PaymentScheme.PACKAGE_BANKPAY); context.StartActivity(new Intent(Intent.ActionView, uri)); return(true); } return(false); }
private async void Play(string track) { if (_isPaused && _player != null) { _isPaused = false; //We are simply paused so just start again _player.Start(); StartForeground(); return; } if (_player == null) { IntializePlayer(); } if (_player.IsPlaying) { return; } try { await _player.SetDataSourceAsync(ApplicationContext, Uri.Parse(track)); var focusResult = _audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain); if (focusResult != AudioFocusRequest.Granted) { //could not get audio focus Console.WriteLine("Could not get audio focus"); } _player.PrepareAsync(); AquireWifiLock(); StartForeground(); } catch (Exception ex) { //unable to start playback log error Console.WriteLine("Unable to start playback: " + ex); } }
public bool Ligar(string numero) { #pragma warning disable CS0618 // O tipo ou membro é obsoleto var context = Forms.Context; #pragma warning restore CS0618 // O tipo ou membro é obsoleto if (context == null) { return(false); } var intent = new Intent(Intent.ActionCall); intent.SetData(Uri.Parse("tel:" + numero)); if (IsIntentAvailable(context, intent)) { context.StartActivity(intent); return(true); } return(false); }
public bool Dials(string phoneNumber) { var context = Form.Context; if (context == null) { return(false); } var intent = new Intent(Intent.ActionCall); intent.SetData(Uri.Parse("tel:" + phoneNumber)); if (IsIntentAvailable(context, intent)) { context.StartActivity(intent); return(true); } return(false); }
public static string GetMediaPath(Context context, Uri uri) { bool afterKitKat = Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat; if (afterKitKat && DocumentsContract.IsDocumentUri(context, uri)) // DocumentProvider { string docId = DocumentsContract.GetDocumentId(uri); if (IsExternalStorageDocument(uri)) // ExternalStorageProvider { string[] split = docId.Split(':'); string type = split[0]; if (string.Equals(type, "primary", StringComparison.OrdinalIgnoreCase)) { return(Android.OS.Environment.ExternalStorageDirectory + "/" + split[1]); } // TODO handle non-primary volumes } else if (IsDownloadsDocument(uri)) // DownloadsProvider { long id; if (!long.TryParse(docId, out id)) { return(null); } Uri contentUri = ContentUris.WithAppendedId(Uri.Parse("content://downloads/public_downloads"), id); return(GetDataColumn(context, contentUri, null, null)); } else if (IsMediaDocument(uri)) // MediaProvider { string[] split = docId.Split(':'); string type = split[0]; Uri contentUri = null; if (string.Equals(type, "image", StringComparison.OrdinalIgnoreCase)) { contentUri = MediaStore.Images.Media.ExternalContentUri; } else if (string.Equals(type, "video", StringComparison.OrdinalIgnoreCase)) { contentUri = MediaStore.Video.Media.ExternalContentUri; } else if (string.Equals(type, "audio", StringComparison.OrdinalIgnoreCase)) { contentUri = MediaStore.Audio.Media.ExternalContentUri; } string selection = "_id=?"; string[] selectionArgs = new string[] { split[1] }; return(GetDataColumn(context, contentUri, selection, selectionArgs)); } } else if (string.Equals(uri.Scheme, "content", StringComparison.OrdinalIgnoreCase)) // MediaStore (and general) { return(GetDataColumn(context, uri, null, null)); } else if (string.Equals(uri.Scheme, "file", StringComparison.OrdinalIgnoreCase)) // File { return(uri.Path); } return(null); }
/// <summary> /// Opens the specified package in the Google Play store /// </summary> private void OpenPlayStorePackage(string packageName) => StartActivity(new Intent(Intent.ActionView) .SetData(Uri.Parse($"https://play.google.com/store/apps/details?id={packageName}")) .SetPackage("com.android.vending"));
/// <summary> /// OnCreate /// </summary> /// <param name="savedInstanceState"></param> protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Bundle b = (savedInstanceState ?? Intent.Extras); bool ran = b.GetBoolean("ran", defaultValue: false); this.title = b.GetString(MediaStore.MediaColumns.Title); this.description = b.GetString(MediaStore.Images.ImageColumns.Description); this.tasked = b.GetBoolean(ExtraTasked); this.id = b.GetInt(ExtraId, 0); this.type = b.GetString(ExtraType); this.front = b.GetInt(ExtraFront); if (this.type == "image/*") { this.isPhoto = true; } this.action = b.GetString(ExtraAction); Intent pickIntent = null; try { pickIntent = new Intent(this.action); if (this.action == Intent.ActionPick) { pickIntent.SetType(type); } else { if (!this.isPhoto) { this.seconds = b.GetInt(MediaStore.ExtraDurationLimit, 0); if (this.seconds != 0) { pickIntent.PutExtra(MediaStore.ExtraDurationLimit, seconds); } } this.saveToAlbum = b.GetBoolean(ExtraSaveToAlbum); pickIntent.PutExtra(ExtraSaveToAlbum, this.saveToAlbum); this.quality = (VideoQuality)b.GetInt(MediaStore.ExtraVideoQuality, (int)VideoQuality.High); pickIntent.PutExtra(MediaStore.ExtraVideoQuality, GetVideoQuality(this.quality)); if (front != 0) { pickIntent.PutExtra(ExtraFront, (int)Android.Hardware.CameraFacing.Front); } if (!ran) { this.path = GetOutputMediaFile(this, b.GetString(ExtraPath), this.title, this.isPhoto, false); Touch(); var targetsNOrNewer = false; try { targetsNOrNewer = (int)Application.Context.ApplicationInfo.TargetSdkVersion >= 24; } catch (Exception appInfoEx) { System.Diagnostics.Debug.WriteLine("Unable to get application info for targetSDK, trying to get from package manager: " + appInfoEx); targetsNOrNewer = false; var appInfo = PackageManager.GetApplicationInfo(Application.Context.PackageName, 0); if (appInfo != null) { targetsNOrNewer = (int)appInfo.TargetSdkVersion >= 24; } } if (targetsNOrNewer && this.path.Scheme == "file") { var photoURI = FileProvider.GetUriForFile(this, Application.Context.PackageName + ".fileprovider", new Java.IO.File(this.path.Path)); GrantUriPermissionsForIntent(pickIntent, photoURI); pickIntent.PutExtra(MediaStore.ExtraOutput, photoURI); } else { pickIntent.PutExtra(MediaStore.ExtraOutput, this.path); } } else { this.path = Uri.Parse(b.GetString(ExtraPath)); } } if (!ran) { StartActivityForResult(pickIntent, this.id); } } catch (Exception ex) { OnMediaPicked(new MediaPickedEventArgs(this.id, ex)); //must finish here because an exception has occured else blank screen Finish(); } finally { if (pickIntent != null) { pickIntent.Dispose(); } } }
/** * Get a file path from a Uri. This will get the the path for Storage Access * Framework Documents, as well as the _data field for the MediaStore and * other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @author paulburke */ // @SuppressLint("NewApi") public static string GetRealPathFromURI_API19(Context context, Uri uri) { bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat; // DocumentProvider if (isKitKat && DocumentsContract.IsDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { string docId = DocumentsContract.GetDocumentId(uri); string[] split = docId.Split(':'); string type = split[0]; if ("primary".Equals(type, StringComparison.InvariantCultureIgnoreCase)) { return(Environment.ExternalStorageDirectory + "/" + split[1]); } // TODO handle non-primary volumes } // DownloadsProvider else if (isDownloadsDocument(uri)) { string id = DocumentsContract.GetDocumentId(uri); Uri contentUri; try { long iid = long.Parse(id); contentUri = ContentUris.WithAppendedId( Uri.Parse("content://downloads/public_downloads"), iid); } catch { return(id); } return(getDataColumn(context, contentUri, null, null)); } // MediaProvider else if (isMediaDocument(uri)) { string docId = DocumentsContract.GetDocumentId(uri); string[] split = docId.Split(':'); string type = split[0]; Uri contentUri = null; if ("image".Equals(type)) { contentUri = MediaStore.Images.Media.ExternalContentUri; } else if ("video".Equals(type)) { contentUri = MediaStore.Video.Media.ExternalContentUri; } else if ("audio".Equals(type)) { contentUri = MediaStore.Audio.Media.ExternalContentUri; } string selection = "_id=?"; string[] selectionArgs = new string[] { split[1] }; return(getDataColumn(context, contentUri, selection, selectionArgs)); } } // MediaStore (and general) else if ("content".Equals(uri.Scheme, StringComparison.InvariantCultureIgnoreCase)) { // Return the remote address if (isGooglePhotosUri(uri)) { return(uri.LastPathSegment); } return(getDataColumn(context, uri, null, null)); } // File else if ("file".Equals(uri.Scheme, StringComparison.InvariantCultureIgnoreCase)) { return(uri.Path); } return(null); }
public static Uri GetAlbumArtUri(long albumId) { return(ContentUris.WithAppendedId(Uri.Parse("content://media/external/audio/albumart"), albumId)); }
public void PerformDial1(string translatedNumber) { var intent = new Intent(Intent.ActionCall); intent.SetData(Uri.Parse("tel:" + translatedNumber)); StartActivity(intent); }
public override bool ShouldOverrideUrlLoading(Android.Webkit.WebView view, string url) { if (!url.StartsWith("http://") && !url.StartsWith("https://") && !url.StartsWith("javascript:") && !url.StartsWith("file:")) { Intent intent = null; try { intent = Intent.ParseUri(url, Intent.UriIntentScheme); //IntentURI처리 Uri uri = Uri.Parse(intent.DataString); context.StartActivity(new Intent(Intent.ActionView, uri)); //해당되는 Activity 실행 return(true); } catch (URISyntaxException ex) { return(false); } catch (ActivityNotFoundException e) { if (intent == null) { return(false); } if (handleNotFoundPaymentScheme(intent.Scheme)) { return(true); //설치되지 않은 앱에 대해 사전 처리(Google Play이동 등 필요한 처리) } String packageName = intent.Package; if (packageName != null) { //packageName이 있는 경우에는 Google Play에서 검색을 기본 Uri uri = Uri.Parse("market://details?id=" + packageName); context.StartActivity(new Intent(Intent.ActionView, uri)); return(true); } return(false); } } else if (url.StartsWith("http://175.115.110.17:8088/Service1.svc")) { try { string temp = url.Replace("http://175.115.110.17:8088/Service1.svc?imp_uid=", ""); if (temp.Contains("&")) { string[] imp_uid = temp.Split('&'); //$"{Element.Uri}" hybridWebViewRenderer.Element.InvokeAction(imp_uid[0]); hybridWebViewRenderer.Element.Uri = null; hybridWebViewRenderer.RemoveAllViews(); hybridWebViewRenderer.RemoveView(view); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw; } } return(false); }
public override System.Boolean OnOptionsItemSelected(IMenuItem item) { switch (item.ItemId) { case Resource.Id.id_action_btn_Add: { ImagePicker.With(this).SetFolderMode(true) .SetCameraOnly(false) .SetFolderTitle("Album") .SetMultipleMode(true) .SetSelectedImages(mImageList) .SetMaxSize(10) .Start(); // GetImageStreamAsync(); break; } case Resource.Id.id_action_btn_remove_all: { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetTitle("提示"); builder.SetMessage("是否要删除所有已选照片?"); builder.SetPositiveButton(Resource.String.str_cn_confrim, (ss, ee) => { mImageAdapter.mImageViewer.RemoveAll(); mImageAdapter.NotifyDataSetChanged(); }); builder.SetNegativeButton(Resource.String.str_cn_cancel, (ss, ee) => { }); builder.Create().Show(); break; } case Resource.Id.id_action_btn_appinfo: { string curInfo = "联系作者:[email protected]\n\n" + "软件版本:\n" + "\n\t版本号 " + mHhiAndroid.GetAppInfo().CurrentVer.ToString() + "\n\t传输协议版本 " + mHhiAndroid.GetAppInfo().NetProtocolVer.ToString() + "\n\n"; string checkResult = mHhiAndroid.CheckVer(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetTitle("提示"); if (checkResult == "uptodate") { builder.SetMessage(curInfo + "已是最新版本"); builder.SetPositiveButton(Resource.String.str_cn_confrim, (sender, e) => { }); } else if (checkResult == "obsoleted") { builder.SetMessage(curInfo + "当前版本已经被废弃不可使用\n请更新"); builder.SetPositiveButton(Resource.String.str_cn_confrim, (ss, ee) => { Intent intent = new Intent(); intent.SetAction("android.intent.action.VIEW"); Uri content_url = Uri.Parse(checkResult); intent.SetData(content_url); StartActivity(intent); }); builder.SetNegativeButton(Resource.String.str_cn_cancel, (ss, ee) => { }); } else { builder.SetMessage(curInfo + "有新版本可以使用\n是否更新?"); builder.SetPositiveButton(Resource.String.str_cn_confrim, (ss, ee) => { Intent intent = new Intent(); intent.SetAction("android.intent.action.VIEW"); Uri content_url = Uri.Parse(checkResult); intent.SetData(content_url); StartActivity(intent); }); builder.SetNegativeButton(Resource.String.str_cn_cancel, (ss, ee) => { }); } builder.Create().Show(); break; } } return(base.OnOptionsItemSelected(item) || mDrawerToggle.OnOptionsItemSelected(item)); }
/** * Get a file path from a Uri. This will get the the path for Storage Access * Framework Documents, as well as the _data field for the MediaStore and * other file-based ContentProviders.<br> * <br> * Callers should check whether the path is local before assuming it * represents a local file. * * @param context The context. * @param uri The Uri to query. * @see #isLocal(string) * @see #getFile(Context, Uri) * @author paulburke */ public static string GetPath(Context context, Uri uri) { #if DEBUG Log.Debug("FilePathHelper -", "Authority: " + uri.Authority + ", Fragment: " + uri.Fragment + ", Port: " + uri.Port + ", Query: " + uri.Query + ", Scheme: " + uri.Scheme + ", Host: " + uri.Host + ", Segments: " + uri.PathSegments.ToString() ); #endif // DocumentProvider if (DocumentsContract.IsDocumentUri(context, uri)) { // LocalStorageProvider if (IsLocalStorageDocument(uri)) { // The path is the id return(DocumentsContract.GetDocumentId(uri)); } // ExternalStorageProvider else if (IsExternalStorageDocument(uri)) { string docId = DocumentsContract.GetDocumentId(uri); string[] split = docId.Split(':'); string type = split[0]; if ("primary".ToLower() == type.ToLower()) { return(Android.OS.Environment.ExternalStorageDirectory + "/" + split[1]); } else { try { var path = $"/storage/{type}/{split[1]}"; // Test if this is working var file = new Java.IO.File(path); if (!file.Exists()) { throw new NonPrimaryExternalStorageNotSupportedException(); } return(path); } catch (Exception) { return(uri.ToString()); } } // TODO handle non-primary volumes } // DownloadsProvider else if (IsDownloadsDocument(uri)) { string id = DocumentsContract.GetDocumentId(uri); if (id.Length > 4 && id.Substring(0, 4) == "raw:") { return(id.Substring(4)); } else { Uri contentUri = ContentUris.WithAppendedId(Uri.Parse("content://downloads/public_downloads"), long.Parse(id)); return(GetDataColumn(context, contentUri, null, null)); } } // MediaProvider else if (IsMediaDocument(uri)) { string docId = DocumentsContract.GetDocumentId(uri); string[] split = docId.Split(':'); string type = split[0]; Uri contentUri = null; if ("image" == type) { contentUri = MediaStore.Images.Media.ExternalContentUri; } else if ("video" == type) { contentUri = MediaStore.Video.Media.ExternalContentUri; } else if ("audio" == type) { contentUri = MediaStore.Audio.Media.ExternalContentUri; } string selection = "_id=?"; string[] selectionArgs = new string[] { split[1] }; return(GetDataColumn(context, contentUri, selection, selectionArgs)); } } // MediaStore (and general) else if ("content".ToLower() == uri.Scheme.ToLower()) { // Return the remote address if (IsGooglePhotosUri(uri)) { return(uri.LastPathSegment); } return(GetDataColumn(context, uri, null, null)); } // File else if ("file".ToLower() == uri.Scheme.ToLower()) { return(uri.Path); } return(uri.ToString()); }
private async void Play() { try { if ((CurrentTrack == null) && (CurrentTrackId == null)) { if (Queue.Count > 0) { Song firstOrDefault = Queue.FirstOrDefault(); if (firstOrDefault != null) { CurrentTrack = firstOrDefault.Url; CurrentTrackId = firstOrDefault.Id; } else { CurrentTrack = null; CurrentTrackId = null; } } else { return; } } Song currentSong = Queue.FirstOrDefault(p => p.Url == CurrentTrack); if (currentSong == null || CurrentTrack == null) { currentSong = Queue.FirstOrDefault(p => p.Id == CurrentTrackId); } Player?.Stop(); Player = null; if (this.paused && Player != null) { this.paused = false; //We are simply paused so just start again Player.PlayWhenReady = true; if (currentSong != null) { if (!string.IsNullOrEmpty(currentSong.Artist) && !string.IsNullOrEmpty(currentSong.Title)) { this.StartForeground(currentSong.Artist + " - " + currentSong.Title); } else if (!string.IsNullOrEmpty(currentSong.Artist)) { this.StartForeground(currentSong.Artist); } else if (!string.IsNullOrEmpty(currentSong.Title)) { this.StartForeground(currentSong.Title); } } this.RegisterRemoteClient(); this.remoteControlClient.SetPlaybackState(RemoteControlPlayState.Playing); this.UpdateMetadata(); return; } if (Player == null) { this.IntializePlayer(); } if (Player.PlayWhenReady) { this.Stop(); } else { //Player.Reset(); this.paused = false; this.StopForeground(true); this.ReleaseWifiLock(); } this.starting = true; var netEase = Mvx.Resolve <INetEase>(); var newSong = new SongNetease { Artist = currentSong.Artist, Title = currentSong.Title, Url = CurrentTrack, Id = currentSong.Id }; if (string.IsNullOrEmpty(newSong.Url)) { var tempsong = await netEase.GetSong(newSong.Id); if (tempsong != null) { tempsong.Id = newSong.Id; tempsong.Title = newSong.Title; tempsong.Artist = newSong.Artist; newSong = tempsong; } } var currenTrackToPlay = (await netEase.FixUrl(newSong, true)).Url; Dictionary <string, string> headers = new Dictionary <string, string>(); if (currenTrackToPlay.StartsWith("http://221.228.64.228/")) { headers.Add("Host", "m1.music.126.net"); } headers.Add( "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); var trackUrl = Uri.Parse(currenTrackToPlay); FrameworkSampleSource sampleSource = new FrameworkSampleSource(Main, trackUrl, headers); TrackRenderer aRenderer = new MediaCodecAudioTrackRenderer(sampleSource, MediaCodecSelector.Default); if (QueueChanged != null) { QueueChanged(this, new EventArgs()); } var focusResult = this.audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain); if (focusResult != AudioFocusRequest.Granted) { //could not get audio focus Console.WriteLine("Could not get audio focus"); } Player.Prepare(aRenderer); Player.PlayWhenReady = true; this.AquireWifiLock(); if (currentSong != null) { if (!string.IsNullOrEmpty(currentSong.Artist) && !string.IsNullOrEmpty(currentSong.Title)) { this.StartForeground(currentSong.Artist + " - " + currentSong.Title); } else if (!string.IsNullOrEmpty(currentSong.Artist)) { this.StartForeground(currentSong.Artist); } else if (!string.IsNullOrEmpty(currentSong.Title)) { this.StartForeground(currentSong.Title); } } this.RegisterRemoteClient(); this.remoteControlClient.SetPlaybackState(RemoteControlPlayState.Buffering); this.UpdateMetadata(); } catch { // ignored } }
/// <summary> /// OnCreate /// </summary> /// <param name="savedInstanceState"></param> protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Bundle b = (savedInstanceState ?? Intent.Extras); bool ran = b.GetBoolean("ran", defaultValue: false); this.title = b.GetString(MediaStore.MediaColumns.Title); this.description = b.GetString(MediaStore.Images.ImageColumns.Description); this.tasked = b.GetBoolean(ExtraTasked); this.id = b.GetInt(ExtraId, 0); this.type = b.GetString(ExtraType); if (this.type == "image/*") { this.isPhoto = true; } this.action = b.GetString(ExtraAction); Intent pickIntent = null; try { pickIntent = new Intent(this.action); if (this.action == Intent.ActionPick) { pickIntent.SetType(type); } else { if (!this.isPhoto) { this.seconds = b.GetInt(MediaStore.ExtraDurationLimit, 0); if (this.seconds != 0) { pickIntent.PutExtra(MediaStore.ExtraDurationLimit, seconds); } } this.saveToAlbum = b.GetBoolean(ExtraSaveToAlbum); pickIntent.PutExtra(ExtraSaveToAlbum, this.saveToAlbum); this.quality = (VideoQuality)b.GetInt(MediaStore.ExtraVideoQuality, (int)VideoQuality.High); pickIntent.PutExtra(MediaStore.ExtraVideoQuality, GetVideoQuality(this.quality)); if (!ran) { this.path = GetOutputMediaFile(this, b.GetString(ExtraPath), this.title, this.isPhoto, this.saveToAlbum); Touch(); pickIntent.PutExtra(MediaStore.ExtraOutput, this.path); } else { this.path = Uri.Parse(b.GetString(ExtraPath)); } } if (!ran) { StartActivityForResult(pickIntent, this.id); } } catch (Exception ex) { OnMediaPicked(new MediaPickedEventArgs(this.id, ex)); } finally { if (pickIntent != null) { pickIntent.Dispose(); } } }