public bool SavePhotoAsync(byte[] data, string directory, string folder, string filename, ref string fullpath) { try { //File picturesDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures); Java.IO.File folderDirectory = null; if (!string.IsNullOrEmpty(folder)) { folderDirectory = new Java.IO.File(directory, folder); folderDirectory.Mkdirs(); } using (Java.IO.File bitmapFile = new Java.IO.File(folderDirectory, filename)) { bitmapFile.CreateNewFile(); using (Java.IO.FileOutputStream outputStream = new Java.IO.FileOutputStream(bitmapFile)) { outputStream.Write(data); } fullpath = bitmapFile.AbsolutePath; } } catch { return(false); } return(true); }
private void PdfViewerControl_DocumentSaveInitiated(object sender, DocumentSaveInitiatedEventArgs args) { MemoryStream stream = args.SavedStream as MemoryStream; string root = null; string fileName = "sample.pdf"; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); } Java.IO.File directory = new Java.IO.File(root + "/Syncfusion"); directory.Mkdir(); Java.IO.File file = new Java.IO.File(directory, fileName); if (file.Exists()) { file.Delete(); } Java.IO.FileOutputStream outputStream = new Java.IO.FileOutputStream(file); outputStream.Write(stream.ToArray()); outputStream.Flush(); outputStream.Close(); AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainView.Context); alertDialog.SetTitle("Save"); alertDialog.SetMessage("The modified document is saved in the below location. " + "\n" + file.Path); alertDialog.SetPositiveButton("OK", (senderAlert, e) => { }); Dialog dialog = alertDialog.Create(); dialog.Show(); }
public static async Task<Android.Net.Uri> DownloadDocument (Context ctx, Android.Net.Uri uriToDownload, string saveFilePath, IProgress<DownloadBytesProgress> progessReporter) { int receivedBytes = 0; int totalBytes = 0; using (var assetFileDescriptor = ctx.ContentResolver.OpenAssetFileDescriptor (uriToDownload, "r")) using (var fileOutputStream = new Java.IO.FileOutputStream (saveFilePath)) using (var inputStream = assetFileDescriptor.CreateInputStream ()) { var buffer = new byte [BufferSize]; totalBytes = (int)assetFileDescriptor.Length; for (;;) { var bytesRead = await inputStream.ReadAsync (buffer, 0, buffer.Length); if (bytesRead == 0) { await Task.Yield(); break; } await fileOutputStream.WriteAsync (buffer, 0, buffer.Length); receivedBytes += bytesRead; if (progessReporter != null) { var args = new DownloadBytesProgress (uriToDownload.ToString (), saveFilePath, receivedBytes, totalBytes); progessReporter.Report(args); } } inputStream.Close (); fileOutputStream.Close (); } var file = new Java.IO.File (saveFilePath); var docUri = Android.Net.Uri.FromFile (file); return docUri; }
private async Task <string> SaveFileToFolder(Android.Net.Uri uri, string fileName) { Android.Net.Uri docUri = Android.Provider.DocumentsContract.BuildDocumentUriUsingTree(uri, Android.Provider.DocumentsContract.GetTreeDocumentId(uri)); string fileFolder = SAFFileUtil.GetPath(this, docUri); Java.IO.File destFolder = new Java.IO.File(fileFolder); Java.IO.File file = new Java.IO.File(destFolder, fileName); Java.IO.File tempFile = new Java.IO.File(TempFilePath); destFolder.Mkdirs(); if (!file.Exists()) { file.CreateNewFile(); } Java.IO.FileInputStream fileInput = new Java.IO.FileInputStream(tempFile); Java.IO.FileOutputStream fileOutput = new Java.IO.FileOutputStream(file, false); while (true) { byte[] data = new byte[1024]; int read = await fileInput.ReadAsync(data, 0, data.Length); if (read <= 0) { break; } await fileOutput.WriteAsync(data, 0, read); } fileInput.Close(); fileOutput.Close(); return(file.AbsolutePath); }
public string Save(MemoryStream stream) { string root = null; string fileName = "SavedDocument.pdf"; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); string filePath = file.Path; if (file.Exists()) { file.Delete(); } Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file); outs.Write(stream.ToArray()); var ab = file.Path; outs.Flush(); outs.Close(); return(filePath); }
public StreamConverter(Java.IO.FileOutputStream fileOutputStream) { _fileOutputStream = fileOutputStream; CanRead = false; CanSeek = false; CanWrite = true; Length = 0; }
private void SavetoSd() { //var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path; //var filePath = System.IO.Path.Combine(sdCardPath, "iootext.txt"); //if (!System.IO.File.Exists(filePath)) //{ // using (System.IO.StreamWriter write = new System.IO.StreamWriter(filePath, true)) // { // write.Write(etSipServer.ToString()); // } //} var dirPath = this.FilesDir + "/KnowPool"; var exists = Directory.Exists(dirPath); var filepath = dirPath + "/cache_data.txt"; Console.WriteLine("Directory Path : " + filepath); if (!exists) { Directory.CreateDirectory(dirPath); if (!System.IO.File.Exists(filepath)) { var newfile = new Java.IO.File(dirPath, "cache_data.txt"); using (Java.IO.FileOutputStream outfile = new Java.IO.FileOutputStream(newfile)) { //string line = "The very first line!"; outfile.Write(System.Text.Encoding.ASCII.GetBytes(login_result_data)); outfile.Flush(); outfile.Close(); } } } else { if (!System.IO.File.Exists(filepath)) { var newfile = new Java.IO.File(dirPath, "cache_data.txt"); using (Java.IO.FileOutputStream outfile = new Java.IO.FileOutputStream(newfile)) { //string line = "The very first line!"; outfile.Write(System.Text.Encoding.ASCII.GetBytes(login_result_data)); outfile.Flush(); outfile.Close(); } } else { using (StreamWriter objStreamWriter = new StreamWriter(filepath, true)) { objStreamWriter.WriteLine(login_result_data); objStreamWriter.Flush(); objStreamWriter.Close(); } } } }
public void Copy(Context context, string fromFileName, Android.Net.Uri toUri, int bufferSize = 1024, CancellationToken?token = null) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(fromFileName)) { throw new ArgumentNullException(nameof(fromFileName)); } if (toUri == null) { throw new ArgumentNullException(nameof(toUri)); } if (!System.IO.File.Exists(fromFileName)) { throw new System.IO.FileNotFoundException(fromFileName); } if (token == null) { token = CancellationToken.None; } var buffer = new byte[bufferSize]; using (var readStream = System.IO.File.OpenRead(fromFileName)) { using (var openFileDescriptor = context.ContentResolver.OpenFileDescriptor(toUri, "w")) { using (var fileOutputStream = new Java.IO.FileOutputStream(openFileDescriptor.FileDescriptor)) { using (var bufferedStream = new System.IO.BufferedStream(readStream)) { int count; while ((count = bufferedStream.Read(buffer, 0, bufferSize)) > 0) { if (token.Value.IsCancellationRequested) { return; } fileOutputStream.Write(buffer, 0, count); } fileOutputStream.Close(); openFileDescriptor.Close(); } } } } }
void WritePrintedPdfDoc(ParcelFileDescriptor destination) { var javaStream = new Java.IO.FileOutputStream(destination.FileDescriptor); var osi = new OutputStreamInvoker(javaStream); using (var mem = new MemoryStream()) { document.WriteTo(mem); var bytes = mem.ToArray(); osi.Write(bytes, 0, bytes.Length); } }
public void Save(string filename, byte[] data) { var filepath = GetFilePath(filename); if (!System.IO.File.Exists(filepath)) { System.IO.File.Create(filepath); } Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(filepath); fos.Write(data); fos.Close(); }
//Download file with WebClient, parse filename from header, write to downloads directory (not async yet!) public string DownloadAndWriteFile(WebView view, string url) { Xamarin.Forms.DependencyService.Get <IMessage>().ShortAlert("Downloading..."); //var pathFile = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads); var pathFile = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads); var absolutePath = pathFile.AbsolutePath; var pathToNewFolder = absolutePath + "/Fixity"; Directory.CreateDirectory(pathToNewFolder); try { WebClient webClient = new WebClient(); webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed); var folder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Fixity"; //DOWNLOAD THE FILE //webClient.DownloadFileAsync(new System.Uri(url), folder + "file.pdf"); //webClient.DownloadFile(new System.Uri(url), pathToNewFolder + "/file.pdf"); //OpenPdf(view, pathToNewFolder + "/file.pdf"); //DOWNLOAD when we dont know the original filename: https://stackoverflow.com/questions/20492355/get-original-filename-when-downloading-with-webclient var data = webClient.DownloadData(new System.Uri(url)); string fileName = ""; // Try to extract the filename from the Content-Disposition header if (!String.IsNullOrEmpty(webClient.ResponseHeaders["Content-Disposition"])) { fileName = webClient.ResponseHeaders["Content-Disposition"].Substring(webClient.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 9).Replace("\"", ""); } if (fileName == "") { fileName = "issue.pdf"; } fileName = System.IO.Path.Combine(pathToNewFolder, fileName); using (var fileOutputStream = new Java.IO.FileOutputStream(fileName)) { fileOutputStream.Write(data); } return(fileName); //OpenPdf(view, fileName); } catch (Exception ex) { Console.WriteLine("ERROR:" + ex.Message); return(""); } }
public static void SaveFileToStorage(Java.IO.File f) { if (f == null) { return; } try { Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(f); fos.Close(); } catch (FileNotFoundException e) { } catch (IOException e) { } }
public override void OnPageFinished(global::Android.Webkit.WebView myWebview, string url) { PdfDocument document = new PdfDocument(); PdfDocument.Page page = document.StartPage(new PdfDocument.PageInfo.Builder(width, height, 1).Create()); myWebview.Draw(page.Canvas); document.FinishPage(page); Stream filestream = new MemoryStream(); Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(fileNameWithPath, false); document.WriteTo(filestream); fos.Write(((MemoryStream)filestream).ToArray(), 0, (int)filestream.Length); fos.Close(); }
public void OnPictureTaken(byte[] data, Camera camera) { Task.Run(() => { var directoryPictures = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); var directory = new Java.IO.File(directoryPictures, Constants.Steepshot); if (!directory.Exists()) { directory.Mkdirs(); } var photoUri = $"{directory}/{Guid.NewGuid()}.jpeg"; var stream = new Java.IO.FileOutputStream(photoUri); stream.Write(data); stream.Close(); var exifInterface = new ExifInterface(photoUri); var orientation = exifInterface.GetAttributeInt(ExifInterface.TagOrientation, 0); if (orientation != 1 && orientation != 0) { var bitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length); bitmap = BitmapUtils.RotateImage(bitmap, _rotationOnShutter); var rotationStream = new System.IO.FileStream(photoUri, System.IO.FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, rotationStream); } var i = new Intent(Context, typeof(PostDescriptionActivity)); i.PutExtra(PostDescriptionActivity.PhotoExtraPath, photoUri); i.PutExtra(PostDescriptionActivity.IsNeedCompressExtraPath, false); Activity.RunOnUiThread(() => { StartActivity(i); Activity.Finish(); if (_progressBar != null) { _progressBar.Visibility = ViewStates.Gone; _shotButton.Visibility = ViewStates.Visible; _flashButton.Enabled = true; _galleryButton.Enabled = true; _revertButton.Enabled = true; _closeButton.Enabled = true; } }); }); }
public void SaveFile(byte[] data, string url) { try { Java.IO.File f = new Java.IO.File(Android.App.Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures), url); f.CreateNewFile(); Java.IO.FileOutputStream fs = new Java.IO.FileOutputStream(f); fs.Write(data); fs.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
private void CreateFileJava(string fileName, byte[] data) { var path = Environment.ExternalStorageDirectory + Java.IO.File.Separator + fileName; var file = new Java.IO.File(path); file.CreateNewFile(); if (file.Exists()) { Java.IO.OutputStream fo = new Java.IO.FileOutputStream(file); fo.Write(data); fo.Close(); Toast.MakeText(this, $"File created at {path}", ToastLength.Short).Show(); } else { Toast.MakeText(this, "Failed to create file", ToastLength.Short).Show(); } }
public ChannelStream(ParcelFileDescriptor parcelFileDescriptor, string mode) { _mode = mode; ParcelFileDescriptor = parcelFileDescriptor; if (mode.Contains("w")) { var outStream = new Java.IO.FileOutputStream(parcelFileDescriptor.FileDescriptor); Channel = outStream.Channel; _stream = outStream; } else { var inStream = new Java.IO.FileInputStream(parcelFileDescriptor.FileDescriptor); Channel = inStream.Channel; _stream = inStream; } }
public async Task <string> SaveImageToLibrary(Stream image, string filename) { var context = contextFactory(); if (context == null) { return(null); } if (string.IsNullOrEmpty(filename)) { throw new ArgumentException(nameof(filename)); } var root = Android.OS.Environment.ExternalStorageDirectory; var imagePath = System.IO.Path.Combine(root.AbsolutePath, filename); var directory = System.IO.Path.GetDirectoryName(imagePath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var imageFile = new Java.IO.File(imagePath); if (!imageFile.Exists()) { imageFile.CreateNewFile(); } using (var file = new Java.IO.FileOutputStream(imageFile)) { var bytes = new byte[image.Length]; image.Read(bytes, 0, bytes.Length); file.Write(bytes, 0, bytes.Length); file.Flush(); } image.Seek(0, SeekOrigin.Begin); var bitmap = await BitmapFactory.DecodeStreamAsync(image); MediaStore.Images.Media.InsertImage(context.ContentResolver, bitmap, imageFile.Name, ""); context.SendBroadcast(new Intent(Intent.ActionMediaScannerScanFile, Android.Net.Uri.Parse("file://" + root))); return(imageFile.AbsolutePath); }
public void btnAdd_OnClick(object sender, EventArgs e) { //get EditText txtTask from view EditText txtTask = FindViewById <EditText>(Resource.Id.txtTask); //create new task Todo objNewTask = new Todo(txtTask.Text) { Location = "", Time = DateTime.Now.Ticks.ToString() }; TodoBL objTodoBL = new TodoBL(); IList <Todo> currentListTodo = new List <Todo>(); //get output stream file to write using (Stream readStream = this.OpenFileInput(new MainActivity().filePath)) { //get current list task currentListTodo = objTodoBL.GetAllTask(readStream); currentListTodo.Add(objNewTask); readStream.Close(); } Java.IO.File dataFile = this.GetFileStreamPath(new MainActivity().filePath); //clear current content file data using (Java.IO.FileOutputStream fileOutput = new Java.IO.FileOutputStream(dataFile.AbsolutePath, false)) { Java.IO.FileWriter fWriter = new Java.IO.FileWriter(fileOutput.FD); fWriter.Write(string.Empty); fWriter.Flush(); fWriter.Close(); } Stream writeStream = this.OpenFileOutput(new MainActivity().filePath, FileCreationMode.Append); objTodoBL.AddTask(currentListTodo, writeStream); //return previous activity this.Finish(); }
public void OnPictureTaken(byte[] data, Camera camera) { Task.Run(() => { var directory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim); var photoUri = $"{directory}/{Guid.NewGuid()}.jpeg"; var stream = new Java.IO.FileOutputStream(photoUri); stream.Write(data); stream.Close(); var exifInterface = new ExifInterface(photoUri); var orientation = exifInterface.GetAttributeInt(ExifInterface.TagOrientation, 0); if (orientation != 1 && orientation != 0) { var bitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length); bitmap = BitmapUtils.RotateImage(bitmap, _rotationOnShutter); var rotationStream = new System.IO.FileStream(photoUri, System.IO.FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, rotationStream); } var model = new GalleryMediaModel { Path = photoUri }; Activity.RunOnUiThread(() => { ((BaseActivity)Activity).OpenNewContentFragment(new PostEditFragment(model)); if (_progressBar != null) { _progressBar.Visibility = ViewStates.Gone; _shotButton.Visibility = ViewStates.Visible; _flashButton.Enabled = true; _galleryButton.Enabled = true; _revertButton.Enabled = true; _closeButton.Enabled = true; } }); }); }
public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName) { try { _location = destinationDirectoryName; if (!_location.EndsWith("/")) { _location += "/"; } var fileInputStream = new FileStream(sourceArchiveFileName, FileMode.Open); var zipInputStream = new ZipInputStream(fileInputStream); ZipEntry zipEntry = null; while ((zipEntry = zipInputStream.NextEntry) != null) { xLog.Debug("UnZipping : " + zipEntry.Name); if (zipEntry.IsDirectory) { DirChecker(zipEntry.Name); } else { var fileOutputStream = new Java.IO.FileOutputStream(_location + zipEntry.Name); for (int i = zipInputStream.Read(); i != -1; i = zipInputStream.Read()) { fileOutputStream.Write(i); } zipInputStream.CloseEntry(); fileOutputStream.Close(); } } zipInputStream.Close(); } catch (Exception ex) { xLog.Error(ex); } }
public async Task SaveJpg(byte[] img) { string path = Path.Combine( Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).Path, "TikiTreiler"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string jpgFilename = Path.Combine(path, DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss-ffff") + ".jpg"); // Doing it the C# way threw a security exception :S. Java.IO.FileOutputStream outStream = new Java.IO.FileOutputStream(jpgFilename); try { outStream.Write(img); } catch (Java.Lang.Exception) { throw new Java.Lang.IllegalArgumentException(); } finally { outStream.Close(); } }
public void CacheData(Context context, string key, byte[] data, bool append) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } if (data == null || data.Length == 0) { return; } using (var cacheDir = GetCacheDir(context)) { var size = cacheDir.TotalSpace - cacheDir.FreeSpace; var dataSize = data.Length; var newSize = dataSize + size; if (newSize > MaxSizeByte) { Clear(cacheDir, newSize - MaxSizeByte); } if (dataSize > MaxSizeByte) { return; } using (var file = new Java.IO.File(cacheDir, key)) { using (var stream = new Java.IO.FileOutputStream(file, append)) { stream.Write(data); stream.Flush(); stream.Close(); } } } }
/// <summary> /// 外部intentで選択したファイルをアプリ専用ディレクトリ領域に一時フィアルとして保存する。 /// </summary> private Java.IO.File SaveBookShelfTempFile(Intent data) { //出力ファイルを用意する Java.IO.File cacheFile = new Java.IO.File(this.ExternalCacheDir, "bookshelf_cache.txt"); try { //入力ファイル using (System.IO.Stream fis = this.ContentResolver.OpenInputStream(data.Data)) { //出力ファイル Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(cacheFile); byte[] buf = new byte[32768]; // 一時バッファ int len = 0; while (true) { len = fis.Read(buf, 0, buf.Length); if (len > 0) { fos.Write(buf, 0, len); } else { break; } } //ファイルに書き込む fos.Flush(); fos.Close(); fis.Close(); } return(cacheFile); } catch (Exception ex) { return(null); } }
public static void SaveVideoToExternalStorage(string path) { Java.IO.File root = Android.OS.Environment.ExternalStorageDirectory; Java.IO.File appDir = new Java.IO.File(root, "Ta7meelVideos"); if (!appDir.Exists()) { if (!appDir.Mkdir()) { return; } } Java.IO.File videoDownloadedFile = new Java.IO.File(path); Java.IO.File file = new Java.IO.File(appDir, videoDownloadedFile.Name); if (!file.Exists()) { try { Java.IO.FileInputStream videoToCopy = new Java.IO.FileInputStream(videoDownloadedFile); Java.IO.FileOutputStream copyOfVideo = new Java.IO.FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = videoToCopy.Read(buf)) > 0) { copyOfVideo.Write(buf, 0, len); } copyOfVideo.Flush(); copyOfVideo.Close(); videoToCopy.Close(); String[] Pathes = new String[] { file.Path }; MediaScannerConnection.ScanFile(Forms.Context, Pathes, null, null); } catch (Exception e) { e.GetType(); } } }
public static async Task <Android.Net.Uri> DownloadDocument(Context ctx, Android.Net.Uri uriToDownload, string saveFilePath, IProgress <DownloadBytesProgress> progessReporter) { int receivedBytes = 0; int totalBytes = 0; using (var assetFileDescriptor = ctx.ContentResolver.OpenAssetFileDescriptor(uriToDownload, "r")) using (var fileOutputStream = new Java.IO.FileOutputStream(saveFilePath)) using (var inputStream = assetFileDescriptor.CreateInputStream()) { var buffer = new byte [BufferSize]; totalBytes = (int)assetFileDescriptor.Length; for (;;) { var bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length); if (bytesRead == 0) { await Task.Yield(); break; } await fileOutputStream.WriteAsync(buffer, 0, buffer.Length); receivedBytes += bytesRead; if (progessReporter != null) { var args = new DownloadBytesProgress(uriToDownload.ToString(), saveFilePath, receivedBytes, totalBytes); progessReporter.Report(args); } } inputStream.Close(); fileOutputStream.Close(); } var file = new Java.IO.File(saveFilePath); var docUri = Android.Net.Uri.FromFile(file); return(docUri); }
public static void Cache(Context context, byte[] data, String name) { Java.IO.File cacheDir = context.CacheDir; long size = GetDirSize(cacheDir); long newSize = data.Length + size; if (newSize > MAX_CACHE_SIZE) { CleanDir(cacheDir, newSize - MAX_CACHE_SIZE); } Java.IO.File file = new Java.IO.File(cacheDir, name); Java.IO.FileOutputStream os = new Java.IO.FileOutputStream(file); try { os.Write(data); } finally { os.Flush(); os.Close(); } }
public async Task <string> Save(byte[] data, string thefileName) { string root = null; string fileName = thefileName; root = await GetPath(); root = Path.Combine(root, Android.OS.Environment.DirectoryDownloads); Java.IO.File file = new Java.IO.File(root, fileName); string filePath = file.Path; if (file.Exists()) { file.Delete(); } Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file); outs.Write(data); var ab = file.Path; outs.Flush(); outs.Close(); return(filePath); }
private void HandleImageCaptured(ImageReader imageReader) { Java.IO.FileOutputStream fos = null; Java.IO.File imageFile = null; var photoSaved = false; try { var image = imageReader.AcquireLatestImage(); var buffer = image.GetPlanes()[0].Buffer; var data = new byte[buffer.Remaining()]; buffer.Get(data); var bitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length); var widthGreaterThanHeight = bitmap.Width > bitmap.Height; image.Close(); string imageFileName = Guid.NewGuid().ToString(); var storageDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); var storageFilePath = storageDir + Java.IO.File.Separator + "AndroidCamera2Demo" + Java.IO.File.Separator + "Photos"; var folder = new Java.IO.File(storageFilePath); if (!folder.Exists()) { folder.Mkdirs(); } imageFile = new Java.IO.File(storageFilePath + Java.IO.File.Separator + imageFileName + ".jpg"); if (imageFile.Exists()) { imageFile.Delete(); } if (imageFile.CreateNewFile()) { fos = new Java.IO.FileOutputStream(imageFile); using (var stream = new MemoryStream()) { if (bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream)) { //We set the data array to the rotated bitmap. data = stream.ToArray(); fos.Write(data); } else { //something went wrong, let's just save the bitmap without rotation. fos.Write(data); } stream.Close(); photoSaved = true; } } } catch (Exception) { // In a real application we would handle this gracefully, likely alerting the user to the error } finally { if (fos != null) { fos.Close(); } RunOnUiThread(UnlockFocus); } // Request that Android display our image if we successfully saved it if (imageFile != null && photoSaved) { var intent = new Intent(Intent.ActionView); var imageUri = Android.Net.Uri.Parse("file://" + imageFile.AbsolutePath); intent.SetDataAndType(imageUri, "image/*"); StartActivity(intent); } }
public bool IsReadOnlyBecauseKitkatRestrictions(IOConnectionInfo ioc) { if (IsLocalFileFlaggedReadOnly(ioc)) return false; //it's not read-only because of the restrictions introduced in kitkat try { //test if we can open //http://www.doubleencore.com/2014/03/android-external-storage/#comment-1294469517 using (var writer = new Java.IO.FileOutputStream(ioc.Path, true)) { writer.Close(); return false; //we can write } } catch (Java.IO.IOException) { //seems like we can't write to that location even though it's not read-only return true; } }
private void playMp3(byte[] mp3SoundByteArray) { try { // create temp file that will hold byte array Java.IO.File tempMp3 = Java.IO.File.CreateTempFile("kurchina", "mp3", CacheDir); tempMp3.DeleteOnExit(); Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(tempMp3); fos.Write(mp3SoundByteArray); fos.Close(); Java.IO.FileInputStream fis = new Java.IO.FileInputStream(tempMp3); player.SetDataSource(fis.FD); player.Prepare(); player.Start(); } catch (Java.IO.IOException ex) { String s = ex.ToString (); ex.PrintStackTrace (); } }
/// <summary> /// Writes data to given filepath whilst recording audio. /// </summary> private void WriteAudioDataToFile() { // Get audio sample length short[] sData = new short[bufferSizeBytes / 2]; Java.IO.FileOutputStream os = null; try { os = new Java.IO.FileOutputStream(filePath); } catch (FileNotFoundException e) { Console.WriteLine(e); } while (isRecording) { // Gets the voice output from microphone to byte format audioRecorder.Read(sData, 0, bufferSizeBytes/2); try { // Writes the data to file from buffer byte[] bData = short2byte(sData); os.Write(bData, 0, bufferSizeBytes); } catch (IOException e) { Console.WriteLine(e); } } try { os.Close(); } catch (IOException e) { Console.WriteLine(e); } }
override public async void Run() { //Android.Media.MediaExtractor extractor; Android.Media.MediaCodec decoder = null; using (var extractor = new Android.Media.MediaExtractor()) //using (Android.Media.MediaCodec decoder = null) { //extractor = new Android.Media.MediaExtractor(); try { await extractor.SetDataSourceAsync(SAMPLE).ConfigureAwait(false); } catch (Exception ex) { var s = ex.ToString(); return; } for (int i = 0; i < extractor.TrackCount; i++) { var format = extractor.GetTrackFormat(i); Log.Debug("Format info: ", format.ToString()); String mime = format.GetString(Android.Media.MediaFormat.KeyMime); if (mime.StartsWith("video/")) { Log.Debug("Format mime: ", mime); //Log.Debug("Format " + MediaFormat.KeyMaxInputSize + ": ", // format.GetInteger(MediaFormat.KeyMaxInputSize).ToString()); Log.Debug("Format " + MediaFormat.KeyWidth + ": ", format.GetInteger(MediaFormat.KeyWidth).ToString()); Log.Debug("Format " + MediaFormat.KeyHeight + ": ", format.GetInteger(MediaFormat.KeyHeight).ToString()); PrintFormatInfo(format); extractor.SelectTrack(i); //decoder = Android.Media.MediaCodec.CreateDecoderByType(mime); //this is where the Xamarin Android VM dies. //decoder.Configure(format, surface, null, 0); break; } } //if (decoder == null) //{ // Android.Util.Log.Error("DecodeActivity", "Can't find video info!"); // return;//can't continue... //} var f = new Java.IO.File(dir+"decode.out"); if (f.Exists()) f.Delete(); f.CreateNewFile(); var f2 = new Java.IO.File(dir + "decode2.out"); if (f2.Exists()) f2.Delete(); f2.CreateNewFile(); //open the file for our custom extractor var inInfo = new System.IO.FileInfo(SAMPLE); if (!inInfo.Exists) { Log.Error("input file not found!", inInfo.FullName); return; } using (var inStream = inInfo.OpenRead()) using (var fs2 = new Java.IO.FileOutputStream(f2))//get an output stream using (var fs = new Java.IO.FileOutputStream(f))//get an output stream { //var inputBuffers = decoder.GetInputBuffers(); //var outputBuffers = decoder.GetOutputBuffers(); var info = new Android.Media.MediaCodec.BufferInfo(); bool started = false, isEOS = false; var sw = new System.Diagnostics.Stopwatch(); long startMs = sw.ElapsedMilliseconds; sw.Start(); byte[] peekBuf = new byte[188]; //for dumping the sample into instead of the decoder. var buffer = Java.Nio.ByteBuffer.Allocate(165000);// decoder.GetInputBuffer(inIndex); var buffEx = new BufferExtractor(); var tmpB = new byte[20000]; while (!interrupted) { //sw.Restart(); if (!isEOS) { int inIndex = 1;// decoder.DequeueInputBuffer(10000); if (inIndex >= 0) { buffer.Position(0);//reset the buffer if (buffer.Position() != 0) Log.Debug("inBuff.Position: ", buffer.Position().ToString()); Log.Debug("inBuff: ", buffer.ToString()); int sampleSize = extractor.ReadSampleData(buffer, 0); if (sampleSize < 0) { // We shouldn't stop the playback at this point, just pass the EOS // flag to decoder, we will get it again from the // dequeueOutputBuffer Log.Debug("DecodeActivity", MediaCodecBufferFlags.EndOfStream.ToString()); //decoder.QueueInputBuffer(inIndex, 0, 0, 0, MediaCodecBufferFlags.EndOfStream); isEOS = true; } else { if (peekBuf.Length < sampleSize) peekBuf = new byte[sampleSize]; peekBuf.Initialize();//clear old data. buffer.Get(peekBuf); buffer.Position(0);//reset for the decoder for (int i = 4; i < peekBuf.Length; ++i) { if (peekBuf[i] == 0x01 && peekBuf[i - 1] == 0x00 && peekBuf[i - 2] == 0x00 && peekBuf[i - 3] == 0x00) Log.Debug("Found h264 start code: ", string.Format("i={0} of {1}", i, sampleSize)); } Log.Debug("ExtractorActivity, sampleSize: ", sampleSize.ToString()); if (!started)//get your parser synced with theirs { do { peekBuf = new byte[188]; await inStream.ReadAsync(peekBuf, 0, peekBuf.Length) .ConfigureAwait(false); buffEx.AddRaw(peekBuf); if (buffEx.outBuffers.Count > 0 && buffEx.outBuffers.Peek().GetPayload().Length != sampleSize) { buffEx.outBuffers.Dequeue();//throw this one away } } while (buffEx.outBuffers.Count == 0); started = true; } else { do { peekBuf = new byte[188]; await inStream.ReadAsync(peekBuf, 0, peekBuf.Length) .ConfigureAwait(false); buffEx.AddRaw(peekBuf); } while (buffEx.outBuffers.Count == 0); started = true; } //write out the vid data. buffer.Limit(sampleSize); buffer.Position(0); //if (tmpB.Length < sampleSize) tmpB = new byte[sampleSize]; buffer.Get(tmpB); fs.Write(tmpB); buffer.Limit(buffer.Capacity());//reset the limit for next sample buffer.Position(0); fs2.Write(buffEx.outBuffers.Dequeue().GetPayload()); if (!inStream.CanRead) isEOS = true;//end of stream. //decoder.QueueInputBuffer(inIndex, 0, sampleSize, extractor.SampleTime, 0); await extractor.AdvanceAsync().ConfigureAwait(false); //extractor.AdvanceAsync(); } } } // All decoded frames have been rendered, we can stop playing now if ((info.Flags & MediaCodecBufferFlags.EndOfStream) != 0) { Android.Util.Log.Debug("DecodeActivity", MediaCodecBufferFlags.EndOfStream.ToString()); break; } } //decoder.Stop(); } } }
private void Reproducir(Cancion cancion) { Action action = new Action(DesactivarControles); Handler.Post(action); byte[] archivo = null; bool huboExcepcion = false; APIGatewayService api = new APIGatewayService(); if (!UtileriasDeArchivos.CancionYaDescargada(cancion.IdArchivo)) { try { archivo = api.DescargarArchivoPorId(cancion.IdArchivo); cancion.CargarMetadatosDeLaCancion(Usuario.Id); } catch (System.Exception) { Toast.MakeText(View.Context, "Error al realizar la descarga, intente de nuevo mas tarde", ToastLength.Long).Show(); huboExcepcion = true; } } else { try { archivo = UtileriasDeArchivos.LeerArchivoPorId(cancion.IdArchivo); } catch (ArgumentException) { huboExcepcion = true; } } if (!huboExcepcion && archivo != null && archivo.Length > 0) { if (Canciones[IndiceActual].Metadatos == null) { bool resultado = false; try { resultado = api.CrearNuevoMetadato(Usuario.Id, Canciones[IndiceActual].Id); } catch (Exception) { Toast.MakeText(View.Context, "No se pudo registrar el MeGusta", ToastLength.Long).Show(); } if (!resultado) { Toast.MakeText(View.Context, "No se pudo registrar el MeGusta", ToastLength.Long).Show(); } else { Canciones[IndiceActual].CargarMetadatosDeLaCancion(Usuario.Id); } } var buttonLike = View.FindViewById <ImageButton>(Resource.Id.ibtnLike); if (cancion.Metadatos.MeGusta) { buttonLike.SetImageDrawable(View.Context.GetDrawable(Resource.Drawable.ic_ss_like)); } else { buttonLike.SetImageDrawable(View.Context.GetDrawable(Resource.Drawable.ic_ss_dislike)); } var buttonReproducir = View.FindViewById <ImageButton>(Resource.Id.ibtnReproducir); buttonReproducir.SetImageDrawable(View.Context.GetDrawable(Resource.Drawable.ic_ss_pausa)); var txtCancion = View.FindViewById <TextView>(Resource.Id.txtNombreCancion); txtCancion.Text = cancion.Nombre; var txtArtista = View.FindViewById <TextView>(Resource.Id.txtNombreArtista); if (cancion.Artistas.FirstOrDefault() != null) { txtArtista.Text = cancion.Artistas.FirstOrDefault().Nombre; } var txtTiempoTotal = View.FindViewById <TextView>(Resource.Id.txtDuracionTotal); TimeSpan tiempoActual = TimeSpan.FromMilliseconds(Reproductor.Duration); txtTiempoTotal.Text = System.String.Format("{0}:{1:D2}", tiempoActual.Minutes, tiempoActual.Seconds); try { Reproductor.Reset(); Java.IO.File archivoTemporal = Java.IO.File.CreateTempFile(cancion.Id, "mp3", Context.CacheDir); archivoTemporal.DeleteOnExit(); Java.IO.FileOutputStream outputStream = new Java.IO.FileOutputStream(archivoTemporal); outputStream.Write(archivo); outputStream.Close(); Java.IO.FileInputStream fis = new Java.IO.FileInputStream(archivoTemporal); Reproductor.SetDataSource(fis.FD); Reproductor.Prepare(); Reproductor.Start(); CancionCorriendo = true; } catch (System.Exception e) { Toast.MakeText(View.Context, e.Message, ToastLength.Long).Show(); } AgregarCancionAHistorial(cancion.Id); } action = new Action(ActivarControles); Handler.Post(action); ActualizadorCorriendo = true; }
public async Task SaveAndView(string fileName, string contentType, MemoryStream stream, PDFOpenContext context) { string exception = string.Empty; string root = null; if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted) { ActivityCompat.RequestPermissions((Activity)Android.App.Application.Context, new string[] { Manifest.Permission.WriteExternalStorage }, 1); } //if (Android.OS.Environment.IsExternalStorageEmulated) //{ // root = Android.OS.Environment.ExternalStorageDirectory.ToString(); //} //else // root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); Java.IO.File myDir = new Java.IO.File(Path.Combine(root, "PDFFiles")); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); } //file.CreateNewFile(); try { Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } if (file.Exists() && contentType != "application/html") { string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); Android.Net.Uri path = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file); intent.SetDataAndType(path, mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); switch (context) { default: case PDFOpenContext.InApp: Android.App.Application.Context.StartActivity(intent); break; case PDFOpenContext.ChooseApp: Android.App.Application.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); break; } } }