protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult (requestCode, resultCode, data); if (resultCode == Result.Ok) { if (requestCode == 0) { _photoAdapter.NotifyDataSetChanged (); System.Console.Out.WriteLine (_temp_IMG_List.Count); } if (requestCode == 1) { _temp_IMG_List.RemoveAt(int.Parse(data.GetStringExtra("delete"))); _photoAdapter.NotifyDataSetChanged (); //System.Console.Out.WriteLine ("delete " + data.GetStringExtra("delete")); } } if (resultCode == Result.Canceled) { if (requestCode == 0) { var deleteFile = new Java.IO.File (_temp_IMG_List [_temp_IMG_List.Count - 1].Path); deleteFile.Delete (); _temp_IMG_List.RemoveAt (_temp_IMG_List.Count-1); _photoAdapter.NotifyDataSetChanged (); } } }
public void Save(string filename, MemoryStream stream) { var root = Android.OS.Environment.DirectoryDownloads; var file = new Java.IO.File(root, filename); if (file.Exists()) file.Delete(); try { var outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { var f = e; } //if (file.Exists()) //{ // var path = Android.Net.Uri.FromFile(file); // var extension = // Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); // var mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); // var intent = new Intent(Intent.ActionOpenDocument); // intent.SetDataAndType(path, mimeType); // Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); //} }
private void SaveExcel(MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, "report.xlsx"); if (file.Exists()) file.Delete(); try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } }
/// <summary> /// Read a file with given path and return a string array with it's entire contents. /// </summary> public static string[] ReadAllLines(string path) { if (path == null) throw new ArgumentNullException("path"); var file = new JFile(path); if (!file.Exists() || !file.IsFile) throw new FileNotFoundException(path); if (!file.CanRead) throw new UnauthorizedAccessException(path); var reader = new BufferedReader(new FileReader(file)); try { var list = new ArrayList<string>(); string line; while ((line = reader.ReadLine()) != null) { list.Add(line); } return list.ToArray(new string[list.Count]); } finally { reader.Close(); } }
private void CreateDirectoryForPictures() { _dir = new File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), "CameraAppDemo"); if (!_dir.Exists()) { _dir.Mkdirs(); } }
public void OpenFile(string filePath, string filename) { var bytes = System.IO.File.ReadAllBytes(filePath); //Copy the private file's data to the EXTERNAL PUBLIC location string externalStorageState = global::Android.OS.Environment.ExternalStorageState; string application = ""; string extension = System.IO.Path.GetExtension(filePath); switch (extension.ToLower()) { case ".doc": case ".docx": application = "application/msword"; break; case ".pdf": application = "application/pdf"; break; case ".xls": case ".xlsx": application = "application/vnd.ms-excel"; break; case ".jpg": case ".jpeg": case ".png": application = "image/jpeg"; break; default: application = "*/*"; break; } var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + filename + extension; System.IO.File.WriteAllBytes(externalPath, bytes); Java.IO.File file = new Java.IO.File(externalPath); file.SetReadable(true); //Android.Net.Uri uri = Android.Net.Uri.Parse("file://" + filePath); Android.Net.Uri uri = Android.Net.Uri.FromFile(file); Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType(uri, application); intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask); try { Xamarin.Forms.Forms.Context.StartActivity(intent); } catch (Exception) { Toast.MakeText(Xamarin.Forms.Forms.Context, "There's no app to open dpf files", ToastLength.Short).Show(); } }
public string SaveAndViewAsync(string filename, MemoryStream stream) { try { string root = null; if (Environment1.IsExternalStorageEmulated) { root = Environment1.ExternalStorageDirectory.ToString(); } else { root = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } //Create directory and file Java.IO.File myDir = new Java.IO.File(root + "/DocScanOpenCV"); myDir.Mkdir(); Java.IO.File myDir1 = new Java.IO.File(root + "/DocScanOpenCV/Docs"); myDir1.Mkdir(); Java.IO.File file = new Java.IO.File(myDir1, filename); //Remove if the file exists if (file.Exists()) { file.Delete(); } //Write the stream into the file FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); if (file.Exists()) { uri1 path = supp.V4.Content.FileProvider.GetUriForFile(andApp.Application.Context, AppInfo.PackageName + ".fileprovider", file); string extension = andwebkit.MimeTypeMap.GetFileExtensionFromUrl(andNet.Uri.FromFile(file).ToString()); string mimeType = andwebkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent openFile = new Intent(); openFile.SetFlags(ActivityFlags.NewTask); openFile.SetFlags(ActivityFlags.GrantReadUriPermission); openFile.SetAction(andContent.Intent.ActionView); openFile.SetDataAndType(path, mimeType); Xamarin.Forms.Forms.Context.StartActivity(Intent.CreateChooser(openFile, "Choose App")); } return("Finish"); } catch (System.Exception ex) { string d = ex.ToString(); return("Error"); // } }
private static Intent createShareIntent(Java.IO.File file) { Intent share = new Intent(Intent.ActionSend); share.SetType("*/*"); share.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(file)); return(share); }
public Files(File file, string path) { this.file = file; Path = file.AbsolutePath; Initialization(); list = new ObservableCollection <Template>(); }
private void InitializeFilesystemAccess() { Java.IO.File externalFilesDir = ((Context)Window.Activity).GetExternalFilesDir((string)null); m_rootDirectory = (externalFilesDir != null) ? "android:SurvivalCraft2.2/files" : "android:SurvivalCraft2.2/files"; if (!Storage.DirectoryExists(m_rootDirectory)) { Storage.CreateDirectory(m_rootDirectory); } }
/// <summary> /// 安装APK文件 /// </summary> /// <param name="activity"></param> /// <param name="filename"></param> /// <param name="dialog"></param> private static void Down(Activity activity, File file, Dialog dialog) { var context = Application.Context; if (!file.Exists()) { return; } else { //通过在代码中写入linux指令修改此apk文件的权限,改为全局可读可写可执行 String[] command = { "chmod", "777", file.Path }; Java.Lang.ProcessBuilder builder = new Java.Lang.ProcessBuilder(command); try { builder.Start(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } } Uri uri; var intent = new Intent(Intent.ActionView); if (Build.VERSION.SdkInt >= BuildVersionCodes.N) { uri = FileProvider.GetUriForFile(context, "com.jshcrb.MyCensus.fileprovider", file); intent.SetAction(Intent.ActionInstallPackage); intent.SetDataAndType(uri, "application/vnd.android.package-archive"); intent.SetFlags(ActivityFlags.NewTask); //FLAG_GRANT_URI_PERMISSION intent.AddFlags(ActivityFlags.GrantPersistableUriPermission); intent.AddFlags(ActivityFlags.GrantPrefixUriPermission); intent.AddFlags(ActivityFlags.GrantWriteUriPermission); intent.AddFlags(ActivityFlags.GrantReadUriPermission); context.StartActivity(intent); } else { uri = Uri.FromFile(file); //intent.SetDataAndType(Android.Net.Uri.Parse("file://" + filePath), "application/vnd.android.package-archive"); intent.SetDataAndType(uri, "application/vnd.android.package-archive"); intent.SetFlags(ActivityFlags.NewTask); context.StartActivity(intent); } activity.RunOnUiThread(() => { dialog.Hide(); dialog.Dismiss(); dialog.Cancel(); }); }
public async Task SaveAndView(string fileName, MemoryStream stream) { string root = null; //Get the root path in android device. /* if (Android.OS.Environment.IsExternalStorageEmulated) * { * root = Android.OS.Environment.ExternalStorageDirectory.ToString(); * } * else*/ string target = @"C:\Users\Fanelle\Documents\TSR\Test"; root = target; /*if (!Directory.Exists(target)) * { * Directory.CreateDirectory(target); * }*/ //Environment.CurrentDirectory = target; // root = Directory.GetCurrentDirectory(); //Create directory and file //string path = @"D:\Python_Files\my_file.py"; /*Java.IO.File file = null; * using (file = File.Create(root)) ;*/ Java.IO.File myDir = new Java.IO.File(root); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); //Remove if the file exists //if (file.Exists()) file.Delete(); //Write the stream into the file FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); //Invoke the created file for viewing /*if (file.Exists()) * { * Android.Net.Uri path = Android.Net.Uri.FromFile(file); * string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); * string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); * Intent intent = new Intent(Intent.ActionView); * intent.SetDataAndType(path, mimeType); * Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); * }*/ }
/// <summary> /// Delete the file with the given path. /// </summary> public static void Delete(string path) { var file = new JFile(path); if (file.IsFile) { file.Delete(); } }
private void GalleryAddPhoto() { Intent MediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); File f = new File(CurrentPhotoPath); Uri contentUri = Uri.FromFile(f); MediaScanIntent.SetData(contentUri); this.SendBroadcast(MediaScanIntent); }
public void OpenFile(string fullPathToFile) { File myFile = new File(fullPathToFile); if (myFile.Exists()) { this.OpenFile(myFile); } }
void DirChecker(String dir) { var file = new Java.IO.File(_location + dir); if (!file.IsDirectory) { file.Mkdirs(); } }
private void deleteRecursive(Java.IO.File fileOrDirectory) { if (fileOrDirectory.IsDirectory) { fileOrDirectory.ListFiles().ToList().ForEach(f => deleteRecursive(f)); } fileOrDirectory.Delete(); }
private void saveOutput(Bitmap croppedImage) { if (saveUri != null) { try { using (var outputStream = ContentResolver.OpenOutputStream(saveUri)) { if (outputStream != null) { croppedImage.Compress(outputFormat, 75, outputStream); } } } catch (Exception ex) { Log.Error(this.GetType().Name, ex.Message); } Bundle extras = new Bundle(); SetResult(Result.Ok, new Intent(saveUri.ToString()) .PutExtras(extras)); } else { Log.Error(this.GetType().Name, "not defined image url"); } //sqlite save ISQLiteConnection conn = null; ISQLiteConnectionFactory factory = new MvxDroidSQLiteConnectionFactory(); var sqlitedir = new Java.IO.File(global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures), "Boruto"); string filename = sqlitedir.Path + "/mysqliteimage.db"; //Toast.MakeText(Application.Context, filename, ToastLength.Long).Show(); Java.IO.File f = new Java.IO.File(filename); conn = factory.Create(filename); conn.CreateTable <Myimage>(); conn.Insert(new Myimage() { Date = "30-12-2016", Imagepath = saveUri.ToString() }); var mycount = 0; foreach (var e in conn.Table <Myimage>().Where(e => e.Date == "30-12-2016")) { mycount++; } //Toast.MakeText(this, mycount.ToString(), ToastLength.Short).Show(); conn.Close(); //sqlite save end croppedImage.Recycle(); Finish(); }
/// <summary> /// Save method used to save the files using <see cref="MemoryStream"/> class. /// </summary> /// <param name="fileName">Name of the output file.</param> /// <param name="contentType">Content type of the output file.</param> /// <param name="stream">The file in the form of <see cref="MemoryStream"/> class.</param> public void Save(string fileName, string contentType, MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); } try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } finally { if (contentType != "application/html") { stream.Dispose(); } } if (file.Exists() && contentType != "application/html") { Android.Net.Uri path = Android.Net.Uri.FromFile(file); string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); path = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file); intent.SetDataAndType(path, mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); } }
//private static String readInstallationFile(File installation) //{ // RandomAccessFile f = new RandomAccessFile(installation, "r"); // byte[] bytes = new byte[(int)f.Length()]; // f.ReadFully(bytes); // f.Close(); // return new Java.Lang.String(bytes).ToString(); //} private static String readInstallationFile(Java.IO.File installation) { RandomAccessFile f = new RandomAccessFile(installation, "r"); byte[] bytes = new byte[(int)f.Length()]; f.ReadFully(bytes); f.Close(); return(new Java.Lang.String(bytes).ToString()); }
private File CreateImageFile() { string ImageFileName = "JPEG_" + DateTime.Now.ToString(); File StorageDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures); File Image = File.CreateTempFile(ImageFileName, ".jpg", StorageDirectory); CurrentPhotoPath = Image.AbsolutePath; return(Image); }
public void ResizeImage(string sourceFile, string targetFile, float maxWidth, float maxHeight) { var permissions = new string[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }; RequestPermissions(permissions, 77); Bitmap bitmapScaled; // First decode with inJustDecodeBounds=true to check dimensions var options = new BitmapFactory.Options() { InJustDecodeBounds = false, InPurgeable = true, }; var image = BitmapFactory.DecodeFile(sourceFile, options); //if (image != null) //{ var sourceSize = new System.Drawing.Size((int)image.GetBitmapInfo().Height, (int)image.GetBitmapInfo().Width); var maxResizeFactor = Math.Min(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height); string targetDir = System.IO.Path.GetDirectoryName(targetFile); if (!Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } Java.IO.File diretorio = new Java.IO.File( Android.OS.Environment.GetExternalStoragePublicDirectory( Android.OS.Environment.DirectoryPictures), "Imagens"); var width = (int)(maxResizeFactor * sourceSize.Width); var height = (int)(maxResizeFactor * sourceSize.Height); bitmapScaled = Bitmap.CreateScaledBitmap(image, 4096, 3072, true); var stream = new Java.IO.FileInputStream(arquivoImagem); using (Stream outStream = System.IO.File.Create($"{targetDir}/Testes.jpg")) { if (targetFile.ToLower().EndsWith("png")) { bitmapScaled.Compress(Bitmap.CompressFormat.Png, 100, outStream); } else { bitmapScaled.Compress(Bitmap.CompressFormat.Jpeg, 80, outStream); } var bytesss = bitmapScaled.ByteCount; var teste = 1; //return bitmapScaled; } //bitmapScaled.Recycle(); }
private bool CopyDirectory(Template tempFile) { foreach (var VARIABLE in Move_copy_file.ListFiles()) { Move_copy_file = VARIABLE; Paste(tempFile); } return(true); }
private void delete_pic() { Java.IO.File fis = new Java.IO.File(absolut_path_pic); if (fis.Exists()) { fis.Delete(); } }
private void CreateDirectoryForPictures() { _dir = new Java.IO.File( Android.OS.Environment.GetExternalStoragePublicDirectory( Android.OS.Environment.DirectoryPictures), "JungleExplorer"); if (!_dir.Exists()) { _dir.Mkdirs( ); } }
private static void CreateDirectoryForPictures() { _dir = new Java.IO.File( Android.OS.Environment.GetExternalStoragePublicDirectory( Android.OS.Environment.DirectoryPictures), "LegionApp"); if (!_dir.Exists()) { _dir.Mkdirs(); } }
public static void RecordVideo(Action <string> callback) { _callback = callback; _destFile = new File(FileHelper.CreateNewVideoPath()); Intent captureVideoIntent = new Intent(MediaStore.ActionVideoCapture); captureVideoIntent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_destFile)); // captureVideoIntent.PutExtra(MediaStore.ExtraVideoQuality, 1); CurrentActivity.StartActivityForResult(captureVideoIntent, RequestCodes.RecordVideo); }
private void CreateDirectoryForPictures() { _dir = new File( Environment.GetExternalStoragePublicDirectory( Environment.DirectoryPictures), "PlanetHeart"); if (!_dir.Exists()) { _dir.Mkdirs(); } }
//cria um diretorio para as imagens private void CreateDirectoryForPictures() { Tela4_CadastrarPatrimonio._dir = new Java.IO.File( Environment.GetExternalStoragePublicDirectory( Environment.DirectoryPictures), "CameraAppDemo"); if (!Tela4_CadastrarPatrimonio._dir.Exists()) { Tela4_CadastrarPatrimonio._dir.Mkdirs(); } }
public Files() { file = new File("/sdcard"); Path = file.AbsolutePath; Initialization(); list = new ObservableCollection <Template>(); }
public static void SelectVideo(Action <string> callback) { _callback = callback; _destFile = new File(FileHelper.CreateNewVideoPath()); Intent selectVideoIntent = new Intent(Intent.ActionPick); selectVideoIntent.SetType("video/*"); selectVideoIntent.SetAction(Intent.ActionGetContent); CurrentActivity.StartActivityForResult(Intent.CreateChooser(selectVideoIntent, "Select Video"), RequestCodes.SelectVideo); }
private void TakeAPicture(object sender, EventArgs eventArgs) { Intent intent = new Intent(MediaStore.ActionImageCapture); _file = new File(_dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid())); intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_file)); StartActivityForResult(intent, 0); }
/** test entry point */ public ExtractMpegFrames(File filesdir, string inputfilename, ref SortedList <long, SparseArray> framelist, int width, int height) { INPUT_FILE = inputfilename; _framelist = framelist; //_FaceFetchDataTasks = FaceFetchDataTasks; _width = width; _height = height; _filesdir = filesdir; ExtractMpegFramesWrapper.runTest(this); }
private void removeTempFiles() { var d = new Java.IO.File(destinationdir); deleteRecursive(d); var zipFile = new Java.IO.File(visualization); zipFile.Delete(); }
public void Save(string fileName, String contentType, MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } Java.IO.File myDir = new Java.IO.File(root + "/Lebenslauf"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); } try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } if (file.Exists() && contentType != "application/html") { Android.Net.Uri path = Android.Net.Uri.FromFile(file); string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType(path, mimeType); //Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); try { Xamarin.Forms.Forms.Context.StartActivity(intent); } catch (Exception) { Toast.MakeText(Xamarin.Forms.Forms.Context, "Keine Anwendung verfügbar zum Anzeigen von WORD", ToastLength.Long).Show(); var urlStore = Device.OnPlatform("https://itunes.apple.com/ca/app/id683290832?mt=8", "https://play.google.com/store/apps/details?id=com.microsoft.office.word", ""); Device.OpenUri(new Uri(urlStore)); } } }
void ShareButtonClicked(object sender, EventArgs e) { if (_logging is ILoggingFile) { //get the file path of the log file to share var path = ((ILoggingFile)_logging).LoggingPath; var file = new Java.IO.File (path); var uri = Android.Net.Uri.FromFile (file); var shareIntent = new Intent (Intent.ActionSend); shareIntent.SetType ("text/plain"); shareIntent.PutExtra (Intent.ExtraStream, uri); StartActivity (Intent.CreateChooser (shareIntent, "Share page to...")); } }
public async Task<bool> Download(string uri, string filename) { string downloadedFolder = "/storage/emulated/0/Download/"; if (App.DownloadsPath != null && !string.IsNullOrEmpty(App.DownloadsPath)) { downloadedFolder = App.DownloadsPath + "/"; } string fileExtenstion = Path.GetExtension(filename); if (fileExtenstion == ".jpg" || fileExtenstion == ".jpeg" || fileExtenstion == ".png") return false; if (System.IO.File.Exists(downloadedFolder + filename)) { string downloadedUri = "file://" + downloadedFolder + filename; Java.IO.File file = new Java.IO.File(new Java.Net.URI( downloadedUri )); Intent videoPlayerActivity = new Intent(Intent.ActionView); videoPlayerActivity.SetDataAndType(Android.Net.Uri.FromFile(file), "video/*"); Activity activity = Forms.Context as Activity; activity.StartActivity(videoPlayerActivity); return true; } App.DownloadID = 0; Android.Net.Uri contentUri = Android.Net.Uri.Parse(uri); Android.App.DownloadManager.Request r = new Android.App.DownloadManager.Request(contentUri); r.SetDestinationInExternalPublicDir(Android.OS.Environment.ExternalStorageDirectory.ToString(), filename); r.AllowScanningByMediaScanner(); r.SetNotificationVisibility(Android.App.DownloadVisibility.VisibleNotifyCompleted); Android.App.DownloadManager dm = (Android.App.DownloadManager)Xamarin.Forms.Forms.Context.GetSystemService(Android.Content.Context.DownloadService); App.DownloadID = dm.Enqueue(r); AndHUD.Shared.Show(MainActivity.GetMainActivity(), "Dowloading Media...", -1, MaskType.Clear, null, () => { dm.Remove(App.DownloadID); }, true, () => { dm.Remove(App.DownloadID); }); return true; }
public void SendMail(MemoryStream stream) { SaveExcel(stream); Intent emailIntent = new Intent(Intent.ActionSend); emailIntent.SetType("plain/text"); Java.IO.File root = Android.OS.Environment.GetExternalStoragePublicDirectory("Syncfusion"); Java.IO.File file = new Java.IO.File(root, "report.xlsx"); if (file.Exists() || file.CanRead()) { Android.Net.Uri uri = Android.Net.Uri.FromFile(file); emailIntent.PutExtra(Intent.ExtraStream, uri); } Forms.Context.StartActivity(Intent.CreateChooser(emailIntent, "Send mail...")); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); Xamarin.Forms.Forms.SetTitleBarVisibility(AndroidTitleBarVisibility.Never); curentActivity = this; CrossPushNotification.Initialize<CrossPushNotificationListener>("572461137328"); ImageCircleRenderer.Init(); AdvancedTimer.Forms.Plugin.Droid.AdvancedTimerImplementation.Init (); File testFile = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.ExternalStorageDirectory.ToString() + "/PurposeColor/"); App.DownloadsPath = testFile.AbsolutePath + "/"; var dir = new Java.IO.File( App.DownloadsPath ); if (!dir.Exists ()) { dir.Mkdirs (); } else { // clearing temp storage of app. try { DateTime fileLastUse = DateTime.UtcNow.AddDays(-2); // DateTime.UtcNow.AddMinutes(-60); DateTime fileCreateDate = DateTime.UtcNow.AddDays(-7); // DateTime.UtcNow.AddMinutes(-60); System.IO.DirectoryInfo tempFileDir = new System.IO.DirectoryInfo(testFile.AbsolutePath); System.IO.FileInfo[] tempFiles = tempFileDir.GetFiles(); foreach (System.IO.FileInfo tempFile in tempFiles) { try { if (tempFile.LastAccessTime < fileLastUse || tempFile.CreationTime < fileCreateDate) { System.IO.File.Delete(tempFile.FullName); } } catch (Exception ex) { var test = ex.Message; } } } catch (Exception ex) { var test = ex.Message; } } LoadApplication(new App()); }
public void PlayAudio(byte[] audioRecording, string fileExtension) { var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var file = new File(documents); var tempAudioFile = File.CreateTempFile(Guid.NewGuid().ToString(), fileExtension, file); tempAudioFile.DeleteOnExit(); var stream = new FileOutputStream(tempAudioFile); stream.Write(audioRecording); stream.Close(); // Tried passing path directly, but kept getting // "Prepare failed.: status=0x1" // so using file descriptor instead var fileStream = new FileInputStream(tempAudioFile); _mediaPlayer.Reset(); _mediaPlayer.SetDataSource(fileStream.FD); _mediaPlayer.Prepare(); _mediaPlayer.Start(); }
public void Save(string fileName, String contentType, MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) file.Delete(); try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } if (file.Exists() && contentType != "application/html") { Android.Net.Uri path = Android.Net.Uri.FromFile(file); string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType(path, mimeType); Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); } }
/// <summary> /// Read a file with given path and return a byte-array with it's entire contents. /// </summary> public static byte[] ReadAllBytes(string path) { if (path == null) throw new ArgumentNullException("path"); var file = new JFile(path); if (!file.Exists() || !file.IsFile) throw new FileNotFoundException(path); if (!file.CanRead) throw new UnauthorizedAccessException(path); var stream = new FileInputStream(file); try { var array = new byte[file.Length()]; stream.Read(array, 0, array.Length); return array; } finally { stream.Close(); } }
public Task<string> GetPictureFromCameraAsync() { return AsyncHelper.CreateAsyncFromCallback<string>(callbackResult => { string path = StorageService.GenerateFilename(StorageType.Image, "png"); File file = new File(path); Intent intent = new Intent(MediaStore.ActionImageCapture); intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(file)); ActivityService.StartActivityForResult(intent, (result, data) => { if (result == Result.Ok) { PerformCrop(Uri.FromFile(file), callbackResult, path); } else { callbackResult(null); } }); }); }
public override void OnCreate () { base.OnCreate (); #region 极光推送相关 //注册Jpush JPushInterface.SetDebugMode (true); JPushInterface.Init (ApplicationContext); //设置基本样式 SetNotificationStyleBasic(); //自定义推送通知栏样式 test SetNotificationStyleCustom(); //设置保留最近5条通知 JPushInterface.SetLatestNotificationNumber(ApplicationContext,5); #endregion #region imageloader 使用二级缓存 //var configuration = ImageLoaderConfiguration.CreateDefault(ApplicationContext);//创建默认的ImageLoader配置参数 //使用自定义参数/sdcard/eldYoung //File cacheDir = StorageUtils.GetOwnCacheDirectory(ApplicationContext, "/sdcard/eldYoung/Cache/HeadImage"); //自定义缓存路径 var cachePath = Android.OS.Environment.ExternalStorageDirectory.ToString()+"/"+"eldyoung/Cache/HeadImage/"; Java.IO.File file = new Java.IO.File(cachePath); if(!file.Exists()) file.Mkdirs();// 创建文件夹 File cacheDir = StorageUtils.GetOwnCacheDirectory(ApplicationContext, cachePath); //自定义缓存路径 var configuration = new ImageLoaderConfiguration.Builder(ApplicationContext).MemoryCacheExtraOptions(480,800) .ThreadPoolSize(3).ThreadPriority(Thread.NormPriority -2).DenyCacheImageMultipleSizesInMemory() .MemoryCache(new UsingFreqLimitedMemoryCache(2*1024*1024)).MemoryCacheSize(2 * 1024 * 1024).DiskCacheSize(50 * 1024 * 1024) .DiskCacheFileNameGenerator(new Md5FileNameGenerator()).TasksProcessingOrder(QueueProcessingType.Lifo).DiskCacheFileCount(100) .DiskCache(new UnlimitedDiskCache(cacheDir)).DefaultDisplayImageOptions(DisplayImageOptions.CreateSimple()).ImageDownloader(new BaseImageDownloader(ApplicationContext, 5 * 1000, 30 * 1000)) .Build(); ImageLoader.Instance.Init(configuration); #endregion #region 百度地图使用 SDKInitializer.Initialize(ApplicationContext); #endregion }
public static void copy(Stream inputStream, File output) { OutputStream outputStream = null; var bufferedInputStream = new BufferedInputStream(inputStream); try { outputStream = new FileOutputStream(output); int read = 0; byte[] bytes = new byte[1024]; while ((read = bufferedInputStream.Read(bytes)) != -1){ outputStream.Write(bytes, 0, read); } } finally { try { if (inputStream != null) { inputStream.Close(); } } finally { if (outputStream != null) { outputStream.Close(); } } } }
public void InitializeMediaPicker() { Log.Debug ("MediaPicker","Selected image source: "+source); switch (source){ case 1: Intent intent = new Intent (); intent.SetType ("image/*"); //Intent.PutExtra (Intent.ExtraAllowMultiple, true); intent.SetAction (Intent.ActionGetContent); StartActivityForResult (Intent.CreateChooser (intent, "Select Picture"), PickImageId); break; case 2: Log.Debug ("CameraIntent","Iniciamos la cámara!"); //STARTTTTT DateTime rightnow = DateTime.Now; string fname = "/plifcap_" + rightnow.ToString ("MM-dd-yyyy_Hmmss") + ".jpg"; Log.Debug ("CameraIntent","Se crea la fecha y el filename!"); Java.IO.File folder = new Java.IO.File (Android.OS.Environment.ExternalStorageDirectory + "/PlifCam"); bool success; bool cfile=false; Java.IO.File file=null; if (!folder.Exists ()) { Log.Debug ("CameraIntent","Crea el folder!"); //aqui el folder no existe y lo creamos success=folder.Mkdir (); if (success) { Log.Debug ("CameraIntent","Sip, lo creó correctamente"); //el folder se creo correctamente! file = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/PlifCam/", fname); cfile = true; }else{ //el folder no se creó, error. } } else { Log.Debug ("CameraIntent","Ya existia el folder!"); //aqui el folder si existe file = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/PlifCam/", fname); cfile = true; apath=file.AbsolutePath; Log.Debug ("CameraIntent","El absolut path sería: "+apath); } if (cfile) { Log.Debug ("CameraIntent", "Si lo creó!!!"); Log.Debug ("CameraIntent","Se crea el archivo"); imgUri = Android.Net.Uri.FromFile (file); Log.Debug ("CameraIntent","se obtiene la URI del archivo"); Log.Debug ("CameraIntent","El absolut path sería: "+apath); if (imgUri == null) { Log.Debug ("CameraIntent", "ESTA NULO DX"); } else { Log.Debug ("CameraIntent","Nope, no es nulo"); } } else { Log.Debug ("CameraIntent", "Error, el archivo no se creó!!!!"); } //ENDDDDD Log.Debug ("CameraIntent", "La URI con la que se iniciara el intent es: "+imgUri); Intent intento = new Intent (Android.Provider.MediaStore.ActionImageCapture); Log.Debug ("CameraIntent",""); intento.PutExtra(Android.Provider.MediaStore.ExtraOutput, imgUri); StartActivityForResult(intento, PickCameraId); break; } }
protected override Java.Lang.Object DoInBackground (params Java.Lang.Object[] @params) { //REALIZAMOS EL PROCESO DE DESCARGA DEL ARCHIVO try{ string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath+"/DescargaImagen/" ; Java.IO.File directory = new Java.IO.File (filePath); if(directory.Exists() ==false) { directory.Mkdir(); } //RECUPERAMOS LA DIRECCION DEL ARCHIVO QUE DESEAMOS DESCARGAR string url_link = @params [0].ToString (); URL url = new URL(url_link); URLConnection conexion = url.OpenConnection(); conexion.Connect (); int lenghtOfFile = conexion.ContentLength; InputStream input = new BufferedInputStream(url.OpenStream()); string NewImageFile = directory.AbsolutePath+ "/"+ url_link.Substring (url_link.LastIndexOf ("/") + 1); OutputStream output = new FileOutputStream(NewImageFile); byte[] data= new byte[lenghtOfFile]; int count; while ((count = input.Read(data)) != -1) { output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); return true; }catch { return false; } }
//*************************************************************************************************** //******************FUNCION QUE SE ENCARGA DEL PROCESO DE DESCARGA DE ARCHIVO*********************** //*************************************************************************************************** void DescargaArchivo(ProgressCircleView tem_pcv, string url_archivo) { //OBTENEMOS LA RUTA DONDE SE ENCUENTRA LA CARPETA PICTURES DE NUESTRO DISPOSITIVO Y LE CONCTENAMOS //EL NOMBRE DE UNA CARPETA NUEVA CARPETA, ES AQUI DONDE GUADAREMOS EL ARCHIVO A DESCARGAR string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath+"/DescargaImagen/" ; Java.IO.File directory = new Java.IO.File (filePath); //VERIFICAMOS SI LA CARPETA EXISTE, SI NO LA CREAMOS if(directory.Exists() ==false) { directory.Mkdir(); } //ESTABLECEMOS LA UBICACION DE NUESTRO ARCHIVO A DESCARGAR URL url = new URL(url_archivo); //CABRIMOS UNA CONEXION CON EL ARCHIVO URLConnection conexion = url.OpenConnection(); conexion.Connect (); //OBTENEMOS EL TAMAÑO DEL ARCHIVO A DESCARGAR int lenghtOfFile = conexion.ContentLength; //CREAMOS UN INPUTSTREAM PARA PODER EXTRAER EL ARCHIVO DE LA CONEXION InputStream input = new BufferedInputStream(url.OpenStream()); //ASIGNAMOS LA RUTA DONDE SE GUARDARA EL ARCHIVO, Y ASIGNAMOS EL NOMBRE CON EL QUE SE DESCARGAR EL ARCHIVO //PARA ESTE CASO CONSERVA EL MISMO NOMBRE string NewFile = directory.AbsolutePath+ "/"+ url_archivo.Substring (url_archivo.LastIndexOf ("/") + 1); //CREAMOS UN OUTPUTSTREAM EN EL CUAL UTILIZAREMOS PARA CREAR EL ARCHIVO QUE ESTAMOS DESCARGANDO OutputStream output = new FileOutputStream(NewFile); byte[] data= new byte[lenghtOfFile]; long total = 0; int count; //COMENSAMOS A LEER LOS DATOS DE NUESTRO INPUTSTREAM while ((count = input.Read(data)) != -1) { total += count; //CON ESTA OPCION REPORTAMOS EL PROGRESO DE LA DESCARGA EN PORCENTAJE A NUESTRO CONTROL //QUE SE ENCUENTRA EN EL HILO PRINCIPAL RunOnUiThread(() => tem_pcv.setPorcentaje ((int)((total*100)/lenghtOfFile))); //ESCRIBIMOS LOS DATOS DELIDOS ES NUESTRO OUTPUTSTREAM output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); //INDICAMOS A NUESTRO PROGRESS QUE SE HA COMPLETADO LA DESCARGA AL 100% RunOnUiThread(() => tem_pcv.setPorcentaje (100)); }
//--->TERMINAN COSAS DE SELECCIONAR IMAGEN DE LA GALERIA<---// //--->INICIAN COSAS DE SELECCIONAR IMAGEN DE LA CAMARA<---// public Android.Net.Uri setImageUri() { // Store image in dcim DateTime rightnow = DateTime.Now; string fname = "/plifcap_" + rightnow.ToString ("MM-dd-yyyy_Hmmss") + ".jpg"; Log.Debug ("Set Image Uri","Se crea la fecha y el filename!"); Java.IO.File folder = new Java.IO.File (Android.OS.Environment.ExternalStorageDirectory + "/PlifCam"); bool success; bool cfile=false; Android.Net.Uri imgUri=null; Java.IO.File file=null; if (!folder.Exists ()) { Log.Debug ("Set Image Uri","Crea el folder!"); //aqui el folder no existe y lo creamos success=folder.Mkdir (); if (success) { Log.Debug ("Set Image Uri","Sip, lo creó correctamente"); //el folder se creo correctamente! file = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/PlifCam/", fname); cfile = true; }else{ //el folder no se creó, error. } } else { Log.Debug ("Set Image Uri","Ya existia el folder!"); //aqui el folder si existe file = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/PlifCam/", fname); cfile = true; } if (cfile) { Log.Debug ("Set Image Uri", "Si lo creó!!!"); Log.Debug ("Set Image Uri","Se crea el archivo"); imgUri = Android.Net.Uri.FromFile (file); Log.Debug ("Set Image Uri","se obtiene la URI del archivo"); if (imgUri == null) { Log.Debug ("Set Image Uri", "ESTA NULO DX"); } else { Log.Debug ("Set Image Uri","Nope, no es nulo"); } string rutacam = GetPathToImage (imgUri); Log.Debug ("Set Image Uri","Se obtiene el PATH"); Log.Debug ("setImageUri", "El PATH obtenido es: "+rutacam); } else { Log.Debug ("Set Image Uri", "Nope, No lo hizo"); } return imgUri; }
/// <summary> /// Open a random access file for the given path, more and access. /// </summary> private static RandomAccessFile Open(string path, FileMode mode, FileAccess access) { var file = new Java.IO.File(path); switch (mode) { case FileMode.CreateNew: if (file.Exists()) throw new IOException("File already exists"); break; case FileMode.Open: if (!file.Exists()) throw new FileNotFoundException(path); break; case FileMode.Append: access = FileAccess.Write; break; } switch (mode) { case FileMode.Create: case FileMode.CreateNew: case FileMode.OpenOrCreate: if (access == FileAccess.Read) { //create empty file, so it can be opened again with read only right, //otherwise an FilNotFoundException is thrown. var additinalAccessFile = new RandomAccessFile(file, "rw"); } break; } var jMode = (access == FileAccess.Read) ? "r" : "rw"; var randomAccessFile = new RandomAccessFile(file, jMode); switch (mode) { case FileMode.Truncate: randomAccessFile.SetLength(0); break; case FileMode.Append: randomAccessFile.Seek(randomAccessFile.Length()); break; } return randomAccessFile; }
private async Task<Bitmap> GetImageFromUrl(string url) { // let's check if the file exists... ContextWrapper cw = new ContextWrapper (this.ApplicationContext); File directory = cw.GetDir("imgDir", FileCreationMode.Private); string[] elements = url.Split (new char[] { '/' }); bool fileExists = false; string fileName = directory + "/" + elements [elements.Length - 1]; if (System.IO.File.Exists (fileName)) { fileExists = true; var imageFile = new Java.IO.File(fileName); Bitmap bitmap = BitmapFactory.DecodeFile(imageFile.AbsolutePath); return bitmap; } if (!fileExists) { using (var client = new HttpClient ()) { var msg = await client.GetAsync (url); if (msg.IsSuccessStatusCode) { using (var stream = await msg.Content.ReadAsStreamAsync ()) { var bitmap = await BitmapFactory.DecodeStreamAsync (stream); File myPath = new File (directory, elements [elements.Length - 1]); try { using (var os = new System.IO.FileStream (myPath.AbsolutePath, System.IO.FileMode.Create)) { bitmap.Compress (Bitmap.CompressFormat.Png, 100, os); } } catch (Exception ex) { System.Console.Write (ex.Message); } return bitmap; } } } } return null; }
public Task<string> GetSoundFromGalleryAsync() { return AsyncHelper.CreateAsyncFromCallback<string>(resultCallback => { Intent intent = new Intent(); intent.SetType("audio/*"); intent.SetAction(Intent.ActionGetContent); var trad = DependencyService.Container.Resolve<ILocalizationService>(); ActivityService.StartActivityForResult(Intent.CreateChooser(intent, trad.GetString("SoundChoice_PickerTitle", "Text")), (result, data) => { string path = null; if (result == Result.Ok) { Uri selectedSound = data.Data; ParcelFileDescriptor parcelFileDescriptor = ActivityService.CurrentActivity.ContentResolver.OpenFileDescriptor(selectedSound, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.FileDescriptor; FileInputStream inputStream = new FileInputStream(fileDescriptor); path = StorageService.GenerateFilename(StorageType.Sound, "3gpp"); File outputFile = new File(path); InputStream inStream = inputStream; OutputStream outStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = inStream.Read(buffer)) > 0) { outStream.Write(buffer, 0, length); } inStream.Close(); outStream.Close(); } resultCallback(path); }); }); }
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { base.OnCreateView (inflater, container, savedInstanceState); Dialog.Window.RequestFeature (WindowFeatures.NoTitle); var view = inflater.Inflate (Resource.Layout.registro_plif, container, false); TextView subefoto = view.FindViewById<TextView> (Resource.Id.subefoto); TextView subeimagen = view.FindViewById<TextView> (Resource.Id.subeimagen); subefoto.SetTypeface(font, TypefaceStyle.Normal); subeimagen.SetTypeface (font, TypefaceStyle.Normal); fotocontainer = view.FindViewById<LinearLayout> (Resource.Id.fotocontainer); subefoto.Click += (object sender, EventArgs e) => { source=1; fossbytes = new List<byte[]>(); GetImage((async (b, p) => { string tag="ImagenGalería"; Log.Debug(tag,"Inicia GETIMAGE"); Java.IO.File f = new Java.IO.File(p[0]); stream = Application.Context.ContentResolver.OpenInputStream(Android.Net.Uri.FromFile(f)); Bitmap temp =BitmapFactory.DecodeStream(stream); fotoperfil = view.FindViewById<ImageView> (Resource.Id.fotoperfil); fotoperfil.SetImageBitmap(temp); fotocontainer.Visibility=ViewStates.Visible; if(temp!=null){ Log.Debug("FOSSBYTES","Inicia conversión a bytes!"); byte[] tmp2 = pliffunctions.PathToByte2(p[0]); Log.Debug("FOSSBYTES","Termina conversión a bytes!"); fossbytes.Add(tmp2); } })); }; subeimagen.Click += (object sender, EventArgs e) => { source=2; fossbytes = new List<byte[]>(); GetImage((async (b, p) => { string tag = "FOTOREGISTRO"; Log.Debug(tag,"Inicia GETIMAGE"); Java.IO.File f = new Java.IO.File(p[0]); stream = Application.Context.ContentResolver.OpenInputStream(Android.Net.Uri.FromFile(f)); Bitmap temp =BitmapFactory.DecodeStream(stream); fotoperfil = view.FindViewById<ImageView> (Resource.Id.fotoperfil); fotoperfil.SetImageBitmap(temp); fotocontainer.Visibility=ViewStates.Visible; if(temp!=null){ Log.Debug("FOSSBYTES","Inicia conversión a bytes!"); byte[] tmp2 = pliffunctions.PathToByte2(p[0]); Log.Debug("FOSSBYTES","Termina conversión a bytes!"); fossbytes.Add(tmp2); } })); }; registrarse = view.FindViewById<Button> (Resource.Id.registrar); TextView nombre = view.FindViewById<TextView> (Resource.Id.nombre); TextView apellidos = view.FindViewById<TextView> (Resource.Id.apellidos); TextView email = view.FindViewById<TextView> (Resource.Id.email); TextView pass1 = view.FindViewById<TextView> (Resource.Id.pass1); TextView pass2 = view.FindViewById<TextView> (Resource.Id.pass2); registrarse.Click += async (object sender, EventArgs e) => { nombre.Text="Gabino"; apellidos.Text="Rutiaga"; email.Text="*****@*****.**"; pass1.Text="hola"; pass2.Text="hola"; if(nombre.Text==""){ Toast.MakeText (Application.Context, "Por favor introduce tu nombre", ToastLength.Long).Show (); }else if(apellidos.Text==""){ Toast.MakeText (Application.Context, "Por favor introduce tus apellidos", ToastLength.Long).Show (); }else if(email.Text==""){ Toast.MakeText (Application.Context, "Por favor introduce tu correo electrónico", ToastLength.Long).Show (); }else if(pass1.Text==""){ Toast.MakeText (Application.Context, "Por favor introduce una contraseña", ToastLength.Long).Show (); }else if(pass1.Text!=pass2.Text){ Toast.MakeText (Application.Context, "Tus contraseñas no coinciden. por favor verifícalas", ToastLength.Long).Show (); }else if(fossbytes==null){ Toast.MakeText (Application.Context, "Sube una foto de perfil!", ToastLength.Long).Show (); }else{ ProgressBar esperaregistro = view.FindViewById<ProgressBar> (Resource.Id.esperaregistro); esperaregistro.Visibility=ViewStates.Visible; registrarse.Visibility=ViewStates.Gone; Dictionary<string, string> datos = new Dictionary<string,string>(); datos.Add("nombre",nombre.Text); datos.Add("apellidos",apellidos.Text); datos.Add("email",email.Text); datos.Add("psw",pass1.Text); /*try{*/ Log.Debug("Try","Inicia envío de datos"); string resp = PostMultiPartFormUI ("http://plif.mx/pages/registNewUser?droid", fossbytes, "nada", "file[]", "image/jpeg", datos, true); Log.Debug("RegistroPlif","Respuesta del servidor: "+resp); JsonValue respuesta = JsonValue.Parse(resp); string registroexitoso=respuesta["registro"]; if(registroexitoso=="true"){ Toast.MakeText (Application.Context, "Por favor activa tu cuenta con el email que te enviamos a "+email.Text, ToastLength.Long).Show (); this.Dismiss(); }else{ Toast.MakeText (Application.Context, "Parece que ya te encuentras registrado pero no has confirmado aún tu cuenta", ToastLength.Long).Show (); esperaregistro.Visibility=ViewStates.Gone; registrarse.Visibility=ViewStates.Visible; } /*}catch(Exception ex){ Log.Debug("ErrorRegistro","ocurrió un errorzote: "+ex); Toast.MakeText (Application.Context, "Ooops! Parece que nuestros sistemas están saturados en este momento. ¿Por que no lo intentas de nuevo en un momento?", ToastLength.Long).Show (); esperaregistro.Visibility=ViewStates.Gone; registrarse.Visibility=ViewStates.Visible; }*/ } }; return view; }
private static Bitmap DecodeFile(File file, int requiredSize) { try { //decode image size BitmapFactory.Options options = new BitmapFactory.Options {InJustDecodeBounds = true}; BitmapFactory.DecodeStream(new FileStream(file.Path, FileMode.OpenOrCreate, FileAccess.ReadWrite,FileShare.ReadWrite), null, options);//FileStream? //Find the correct scale value. It should be the power of 2. int tempWidth = options.OutWidth; int tempHeight = options.OutHeight; var scale = 1; while(true) { if (tempWidth / 2 < requiredSize || tempHeight / 2 < requiredSize) break; tempWidth/=2; tempHeight/=2; scale*=2; } //decode with inSampleSize BitmapFactory.Options options2 = new BitmapFactory.Options {InSampleSize = scale}; return BitmapFactory.DecodeStream(new FileStream(file.Path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite), null, options2);//FileStream? } catch(Exception e) { } return null; }
//--->TERMINAN COSAS DE SELECCIONAR IMAGEN DE LA CAMARA<---// //INICIA PROCESAR IMAGENES public void ProcesarImagenes (GridLayout imgcomprev, int limite, TextView imgrestantes){ if(imgcount<limite){ GetImage(((b, p) => { int countimage = p.Count; Log.Debug("GetImage","Imagenes en el list: "+countimage); int imgcount2=imgcount+countimage; Log.Debug("GetImage","Imagenes totales: "+imgcount2); if(imgcount2>limite){ //int total = limite-imgcount; var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition); Snackbar .Make (fabee, "No puedes publicar mas de "+limite+" imágenes!", Snackbar.LengthLong) .SetAction ("Ok", (view) => { }) .Show (); }else{ //ya aqui se hace lo de poner cada imagen imgcount=imgcount2; Log.Debug("GetImage","Nuevo imgcount: "+imgcount); for(int i=0; i<countimage; i++){ //filenameres= p[i].Substring (p[i].LastIndexOf ("/") + 1); //fileextres= filenameres.Substring (filenameres.LastIndexOf(".")+1); //Si por algún acaso la memoria no ha sido liberada, la liberamos primero. if (imagencomentario != null && !imagencomentario.IsRecycled) { imagencomentario.Recycle(); imagencomentario = null; } Java.IO.File f = new Java.IO.File(p[i]); stream = this.ContentResolver.OpenInputStream(Android.Net.Uri.FromFile(f)); imagencomentario=BitmapFactory.DecodeStream(stream); //POR AHORA VAMOS A QUITAR ESTO PARA QUE LO HAGA MAS RAPIDO Y DEJAMOS QUE EL SERVIDOR SE ENCARGUE /* try{ Android.Media.ExifInterface ei = new Android.Media.ExifInterface(p[i]); var orientation= ei.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, -1); Log.Debug("GetImageCamera","El orientation es: "+orientation); if(orientation==1){ //No hagas nada, si está bien la imagen. No tiene caso .-. }else{ Log.Debug("Orientation", "Inicia Mutable"); Bitmap mutable; Canvas cnv; Matrix matrix; Log.Debug("Orientation", "Termina Mutable"); Log.Debug("Orientation", "Inicia Switch"); switch(orientation){ case 6: //90 grados mutable = imagencomentario.Copy(Bitmap.Config.Argb8888, true); cnv = new Canvas(mutable); matrix = new Matrix(); Log.Debug("Orientation", "90 Grados"); matrix.PostRotate(90); imagencomentario=Bitmap.CreateBitmap(mutable, 0, 0, imagencomentario.Width, imagencomentario.Height, matrix, true); break; case 3: //180 grados mutable = imagencomentario.Copy(Bitmap.Config.Argb8888, true); cnv = new Canvas(mutable); matrix = new Matrix(); Log.Debug("Orientation", "180 Grados"); matrix.PostRotate(180); imagencomentario=Bitmap.CreateBitmap(mutable, 0, 0, imagencomentario.Width, imagencomentario.Height, matrix, true); break; case 8: //270 grados mutable = imagencomentario.Copy(Bitmap.Config.Argb8888, true); cnv = new Canvas(mutable); matrix = new Matrix(); Log.Debug("Orientation", "270 Grados"); matrix.PostRotate(270); imagencomentario=Bitmap.CreateBitmap(mutable, 0, 0, imagencomentario.Width, imagencomentario.Height, matrix, true); break; default: Log.Debug("Orientation", "0 Grados (0 360, como se quiera ver :P)"); //0 grados //No hagas nada break; }; Log.Debug("Orientation", "Termina Switch"); }//ELSE orientation = 1 }catch(Exception ex){ Log.Debug("Orientation", "ERROR! Posiblemente no hay EXIF: "+ex); } */ if(imagencomentario!=null){ //Toast.MakeText(this, "Si se creó el Bitmap!!!", ToastLength.Long).Show(); //Lo añadimos a la lista //Bitmap tmp = imagencomentario; Log.Debug("FOSSBYTES","Inicia conversión a bytes!"); byte[] tmp2 = PathToByte2(p[i]); Log.Debug("FOSSBYTES","Termina conversión a bytes!"); fossbytes.Add(tmp2); //Toast.MakeText(this, "Elementos en lista: "+contenedorimagenes.Count, ToastLength.Long).Show(); //aqui haremos el img //Creamos el imageview con sus parámetros ImageView prev = new ImageView(this); imgcomprev.AddView(prev); GridLayout.LayoutParams lp = new GridLayout.LayoutParams(); lp.SetMargins(15,15,0,15); lp.Width=130; lp.Height=130; prev.LayoutParameters=lp; prev.SetScaleType(ImageView.ScaleType.CenterCrop); prev.SetImageBitmap(Bitmap.CreateScaledBitmap(imagencomentario, 175, 175, false)); //prev.StartAnimation(bounce); //imgcount++; //Liberamos la memoria Inmediatamente! if (imagencomentario != null && !imagencomentario.IsRecycled) { imagencomentario.Recycle(); imagencomentario = null; } //Mala idea, esto causó que tronara .-. si lo voy a hacer pero cuando no tenga que usarlo }else{//por si algun acaso intenta procesar una ruta null var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition); Snackbar .Make (fabee, "Ocurrió un error. Por favor intenta con una imágen diferente", Snackbar.LengthLong) .SetAction ("Ok", (view) => { }) .Show (); break; } }//TERMINA EL FOR PARA CADA IMAGEN int restantes=limite-imgcount; if(restantes==0){ imgrestantes.Text="¡Excelente!"; }else{ imgrestantes.Text="Puedes cargar "+restantes+" imágenes más!"; } }//TERMINA EL ELSE DE COMPROBAR SI HAY MAS IMAGENES DE LAS QUE SE PUEDEN CARGAR }));//GETIMAGE }else{ var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition); Snackbar .Make (fabee, "Solo puedes subir hasta 3 imágenes!", Snackbar.LengthLong) .SetAction ("Ok", (view) => { }) .Show (); }//ELSE COUNTIMAGES < 3 }
//TERMINA PROCESAR IMAGENES public static byte[] PathToByte2(string path){ //byte[] pathData=null; Log.Debug ("ImageToByte", "Inicia path to byte"); Log.Debug ("ImageToByte", "Se crea el nuevo file"); var imgFile = new Java.IO.File(path); Log.Debug ("ImageToByte", "Se crea el nuevo stream"); var stream = new Java.IO.FileInputStream(imgFile); Log.Debug ("ImageToByte", "Se Crea el archivo Byte"); var bytes = new byte[imgFile.Length()]; Log.Debug ("ImageToByte", "Se hace el Stream Read"); stream.Read(bytes); stream.Close (); stream.Dispose (); return bytes; }
/// <summary> /// 下载apk文件 /// </summary> private void DownloadApk() { URL url = null; Stream instream = null; FileOutputStream outstream = null; HttpURLConnection conn = null; try { url = new URL(Global.AppPackagePath); //创建连接 conn = (HttpURLConnection) url.OpenConnection(); conn.Connect(); conn.ConnectTimeout =20000; //获取文件大小 var filelength = conn.ContentLength; instream = conn.InputStream; var file = new Java.IO.File(FILE_PATH); if(!file.Exists()) { file.Mkdir(); } outstream = new FileOutputStream(new Java.IO.File(saveFileName)); int count =0; //缓存 byte[] buff = new byte[1024]; //写入文件中 do { int numread = instream.Read(buff,0,buff.Length); count+=numread; //计算进度条位置 progress = (int)(((float)count/filelength)*100); //更新进度---- other question mProgressbar.Progress = progress; if(numread<=0) { //下载完成,安装新apk Task.Factory.StartNew(InStallApk); break; } //写入文件 outstream.Write(buff,0,numread); } while(!cancelUpdate);//点击取消,停止下载 } catch(Exception ex) { Android.Util.Log.Error (ex.StackTrace,ex.Message); } finally { if (instream != null) instream.Close (); if (outstream != null) outstream.Close (); if(conn!=null) conn.Disconnect (); } dowloadDialog.Dismiss (); }
protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); SetContentView (Resource.Layout.registro_plif); mToolbar = FindViewById<SupportToolBar> (Resource.Id.toolbar); mScrollView = FindViewById<ScrollView> (Resource.Id.scrollView); SetSupportActionBar (mToolbar); //ESTA ES LA FLECHA PARA ATRÁS SupportActionBar.SetHomeAsUpIndicator (Resource.Drawable.ic_arrow_back); SupportActionBar.SetDisplayHomeAsUpEnabled (true); //SupportActionBar.SetHomeButtonEnabled (true); SupportActionBar.Title = "Formar parte de Plif"; mToolbar.SetBackgroundColor (Color.Argb (255, 51, 150, 209)); //INICIA LO QUE COPIE DEL FRAGMENT font = Typeface.CreateFromAsset(Application.Context.Assets, "Fonts/fa.ttf"); TextView subefoto = FindViewById<TextView> (Resource.Id.subefoto); TextView subeimagen = FindViewById<TextView> (Resource.Id.subeimagen); subefoto.SetTypeface(font, TypefaceStyle.Normal); subeimagen.SetTypeface (font, TypefaceStyle.Normal); fotocontainer = FindViewById<LinearLayout> (Resource.Id.fotocontainer); subefoto.Click += (object sender, EventArgs e) => { source=1; fossbytes=null; fossbytes = new List<byte[]>(); GetImage((async (b, p) => { string tag="ImagenGalería"; Log.Debug(tag,"Inicia GETIMAGE"); Java.IO.File f = new Java.IO.File(p[0]); stream = Application.Context.ContentResolver.OpenInputStream(Android.Net.Uri.FromFile(f)); Bitmap temp =BitmapFactory.DecodeStream(stream); fotoperfil = FindViewById<ImageView> (Resource.Id.fotoperfil); fotoperfil.SetImageBitmap(temp); fotocontainer.Visibility=ViewStates.Visible; if(temp!=null){ Log.Debug("FOSSBYTES","Inicia conversión a bytes!"); byte[] tmp2 = pliffunctions.PathToByte2(p[0]); Log.Debug("FOSSBYTES","Termina conversión a bytes!"); fossbytes.Add(tmp2); } })); }; subeimagen.Click += (object sender, EventArgs e) => { source=2; fossbytes=null; fossbytes = new List<byte[]>(); GetImage((async (b, p) => { string tag = "FOTOREGISTRO"; Log.Debug(tag,"Inicia GETIMAGE"); Java.IO.File f = new Java.IO.File(p[0]); stream = Application.Context.ContentResolver.OpenInputStream(Android.Net.Uri.FromFile(f)); Bitmap temp =BitmapFactory.DecodeStream(stream); fotoperfil = FindViewById<ImageView> (Resource.Id.fotoperfil); fotoperfil.SetImageBitmap(temp); fotocontainer.Visibility=ViewStates.Visible; if(temp!=null){ Log.Debug("FOSSBYTES","Inicia conversión a bytes!"); byte[] tmp2 = pliffunctions.PathToByte2(p[0]); Log.Debug("FOSSBYTES","Termina conversión a bytes!"); fossbytes.Add(tmp2); } })); }; registrarse = FindViewById<Button> (Resource.Id.registrar); TextView nombre = FindViewById<TextView> (Resource.Id.nombre); TextView apellidos = FindViewById<TextView> (Resource.Id.apellidos); TextView email = FindViewById<TextView> (Resource.Id.email); TextView pass1 = FindViewById<TextView> (Resource.Id.pass1); TextView pass2 = FindViewById<TextView> (Resource.Id.pass2); registrarse.Click += async (object sender, EventArgs e) => { nombre.Text="Gabino"; apellidos.Text="Rutiaga"; email.Text="*****@*****.**"; pass1.Text="hola"; pass2.Text="hola"; if(nombre.Text==""){ Toast.MakeText (Application.Context, "Por favor introduce tu nombre", ToastLength.Long).Show (); }else if(apellidos.Text==""){ Toast.MakeText (Application.Context, "Por favor introduce tus apellidos", ToastLength.Long).Show (); }else if(email.Text==""){ Toast.MakeText (Application.Context, "Por favor introduce tu correo electrónico", ToastLength.Long).Show (); }else if(pass1.Text==""){ Toast.MakeText (Application.Context, "Por favor introduce una contraseña", ToastLength.Long).Show (); }else if(pass1.Text!=pass2.Text){ Toast.MakeText (Application.Context, "Tus contraseñas no coinciden. por favor verifícalas", ToastLength.Long).Show (); }else if(fossbytes==null){ Toast.MakeText (Application.Context, "Sube una foto de perfil!", ToastLength.Long).Show (); }else{ ProgressBar esperaregistro = FindViewById<ProgressBar> (Resource.Id.esperaregistro); esperaregistro.Visibility=ViewStates.Visible; registrarse.Visibility=ViewStates.Gone; Log.Debug("FOSSBYTES","CANTIDAD DE ARCHIVOS EN EL FOSSBYTES ARRAY: "+fossbytes.Count()); datos = new Dictionary<string,string>(); datos.Add("nombre",nombre.Text); datos.Add("apellidos",apellidos.Text); datos.Add("email",email.Text); datos.Add("psw",pass1.Text); try{ Log.Debug("Try","Inicia envío de datos desde REGISTRO"); string resp = await plifserver.PostMultiPartForm ("http://plif.mx/pages/registNewUser?droid", fossbytes, "nada", "file[]", "image/jpeg", datos, true); Log.Debug("RegistroPlif","Respuesta del servidor: "+resp); JsonValue respuesta = JsonValue.Parse(resp); string registroexitoso=respuesta["registro"]; if(registroexitoso=="true"){ Toast.MakeText (Application.Context, "Por favor activa tu cuenta con el email que te enviamos a "+email.Text, ToastLength.Long).Show (); Finish(); }else{ Toast.MakeText (Application.Context, "Parece que ya te encuentras registrado pero no has confirmado aún tu cuenta", ToastLength.Long).Show (); esperaregistro.Visibility=ViewStates.Gone; registrarse.Visibility=ViewStates.Visible; } }catch(Exception ex){ Log.Debug("ErrorRegistro","ocurrió un errorzote: "+ex); Toast.MakeText (Application.Context, "Ooops! Parece que nuestros sistemas están saturados en este momento. ¿Por que no lo intentas de nuevo en un momento?", ToastLength.Long).Show (); esperaregistro.Visibility=ViewStates.Gone; registrarse.Visibility=ViewStates.Visible; } } }; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.ac_home); Java.IO.File testImageOnSdCard = new Java.IO.File("/mnt/sdcard", TEST_FILE_NAME); if (!testImageOnSdCard.Exists()) { CopyTestImageToSdCard(testImageOnSdCard); } }
private void InStallApk() { var file = new Java.IO.File (saveFileName); if (!file.Exists ()) { return; } //通过Intent安装新的apk文件 Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType (Android.Net.Uri.Parse ("file://"+saveFileName.ToString()), "application/vnd.android.package-archive"); context.StartActivity (intent); }