Esempio n. 1
0
        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();
            }
        }
        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"));
            //}
        }
Esempio n. 3
0
 /// <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 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"));

            }
        }
        public void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, MemoryStream filestream)
        {
            string exception = string.Empty;
            string root      = null;

            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
            {
                root = System.Environment.GetFolderPath(System.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(filestream.ToArray());

                outs.Flush();
                outs.Close();
            }
            catch (Exception e)
            {
                exception = e.ToString();
            }

            Intent email = new Intent(Android.Content.Intent.ActionSend);
            var    uri   = FileProvider.GetUriForFile(this.m_context, Application.Context.PackageName + ".provider", file);

            //file.SetReadable(true, true);
            email.PutExtra(Android.Content.Intent.ExtraSubject, subject);
            email.PutExtra(Intent.ExtraStream, uri);
            email.SetType("application/pdf");

            MainActivity.BaseActivity.StartActivity(email);
        }
Esempio n. 7
0
        // 判断文件是否存在
        public static bool fileIsExists(string strFile)
        {
            try
            {
                Java.IO.File f = new Java.IO.File(strFile);
                if (!f.Exists())
                {
                    return(false);
                }
            }
            catch (Java.Lang.Exception e)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 8
0
        public static void ExportData(Context context)
        {
            BackupInfo backupInfo = new BackupInfo();

            backupInfo.Date            = DateTime.Now;
            backupInfo.UniqueId        = Guid.NewGuid();
            backupInfo.DatabaseVersion = DatabaseHelper.GetVersion(context);
            backupInfo.PackageName     = context.PackageName;
            try
            {
                backupInfo.AppVersionCode = context.ApplicationContext.PackageManager.GetPackageInfo(context.PackageName, 0).VersionCode;
                backupInfo.AppVersionName = context.ApplicationContext.PackageManager.GetPackageInfo(context.PackageName, 0).VersionName;
            }
            catch (Exception ex)
            {
                NLog.LogManager.GetCurrentClassLogger().Error(ex);
            }
            String backupInfoFileName = SaveBackupInfo(context, backupInfo);

            Java.IO.File  file         = new Java.IO.File(GlobalClass.GetLogDirectory(context));
            List <String> logFilePaths = new List <string>();

            if (file.Exists())
            {
                Java.IO.File[] logFiles = file.ListFiles(new FileNameFilter());
                foreach (Java.IO.File f in
                         logFiles)
                {
                    logFilePaths.Add(f.AbsolutePath);
                }
            }
            List <String> files = new List <string>();

            files.Add(backupInfoFileName);
            foreach (var appId in VdmServiceHandler.GetAppIds(context))
            {
                files.Add(DatabaseHelper.GetDatabaseFilePath(appId));
            }
            files.AddRange(logFilePaths);
            string zipFilename = CreateBackupName();

            Zip(context, files, zipFilename);
            String path = Path.Combine(context.ExternalCacheDir.AbsolutePath);

            MediaScannerConnection.ScanFile(context, new String[] { path }, null, null);
        }
Esempio n. 9
0
        /// <summary>
        /// This must be called from main ui thread only...
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cmd"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        public static async Task <int> Run(Context context, string cmd, Action <string> logger = null)
        {
            try
            {
                TaskCompletionSource <int> source = new TaskCompletionSource <int>();

                await Init(context);

                if (!_initialized)
                {
                    if (!_ffmpegFile.Exists())
                    {
                        ResultString = "Ffmpeg missing";
                    }
                    else if (!_ffmpegFile.CanExecute())
                    {
                        ResultString = "Ffmpeg cant execute";
                    }

                    source.SetResult(-1);
                    return(await source.Task);
                }

                await Task.Run(() =>
                {
                    try
                    {
                        int n = _Run(context, cmd, logger);
                        source.SetResult(n);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex);
                        source.SetException(ex);
                    }
                });

                return(await source.Task);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);

                throw ex;
            }
        }
Esempio n. 10
0
        private static Java.IO.File getOutputMediaFile()
        {
            string extr = Android.OS.Environment.ExternalStorageDirectory.ToString();

            Java.IO.File mFolder = new Java.IO.File(extr + "/TMMFOLDER");
            if (!mFolder.Exists())
            {
                mFolder.Mkdir();
            }
            String timeStamp = new Java.Text.SimpleDateFormat("yyyyMMdd_HHmmss",
                                                              Locale.Default).Format(new Date());

            Java.IO.File mediaFile;
            mediaFile = new Java.IO.File(mFolder.AbsolutePath + Java.IO.File.Separator
                                         + "IMG_" + timeStamp + ".jpg");
            return(mediaFile);
        }
Esempio n. 11
0
        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..."));
        }
Esempio n. 12
0
        //Method to save document as a file in Android and view the saved document
        public void SaveAndView(string fileName, String contentType, MemoryStream stream)
        {
            string root = null;

            //Get the root path in android device.
            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
            {
                root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }

            //Create directory and file
            Java.IO.File myDir = new Java.IO.File(root + "/Balances");
            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"));
            //}
        }
        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());
        }
        private string GetFilename()
        {
            WvlLogger.Log(LogType.TraceAll, "GetFilename()");
            string filepath = Android.OS.Environment.ExternalStorageDirectory.Path;

            Java.IO.File file = new Java.IO.File(filepath, AUDIO_RECORDER_FOLDER);

            if (!file.Exists())
            {
                file.Mkdirs();
            }

            var result = (file.AbsolutePath + "/" + DateTime.Now.Millisecond.ToString() + AUDIO_RECORDER_FILE_EXT_WAV);

            wavFileName = result;
            WvlLogger.Log(LogType.TraceAll, "GetFilename() : " + result);
            return(result);
        }
        // Implemented functions for files
        public async Task <string> GetNewSongName()
        {
            int    attempt  = 0;
            string testName = "";

            while (true)
            {
                attempt++;
                testName = "Song" + attempt;
                Java.IO.File file = new Java.IO.File(testName);
                if (file.Exists())
                {
                    continue;
                }
                break;
            }
            return(testName);
        }
Esempio n. 16
0
        //static {
        //init();
        //    }

        /**
         * Inits the.
         */
        public static void init()
        {
            //        DEBUG = false;
            //        INFO = false;
            //        WARN = false;
            //        ERROR = false;

            if (initialized)
            {
                return;
            }

            DEBUG = (LOGCAT_LEVEL <= LOG_LEVEL_DEBUG);
            INFO  = (LOGCAT_LEVEL <= LOG_LEVEL_INFO);
            WARN  = (LOGCAT_LEVEL <= LOG_LEVEL_WARN);
            ERROR = (LOGCAT_LEVEL <= LOG_LEVEL_ERROR);

            try
            {
                Java.IO.File sdRoot = getSDRootFile();
                if (sdRoot != null)
                {
                    Java.IO.File logFile = new Java.IO.File(sdRoot, LOG_FILE_NAME);
                    if (!logFile.Exists())
                    {
                        logFile.CreateNewFile();
                    }

                    Log.Debug(LOG_TAG_STRING, TAG + " : Log to file : " + logFile);
                    if (logStream != null)
                    {
                        logStream.Close();
                    }
                    FileStream file = new FileStream(logFile.Path, FileMode.Open);
                    logStream   = new PrintStream(file, true);
                    initialized = true;
                }
                logFileChannel = getFileLock();
            }
            catch (Java.Lang.Exception e)
            {
                Log.Error(LOG_TAG_STRING, "init log stream failed", e);
            }
        }
Esempio n. 17
0
        public static void WritFile(string path, string fileName, string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return;
            }
            string filePath = path + fileName;

            Java.IO.File     file             = new Java.IO.File(filePath);
            FileOutputStream fileOutputStream = null;

            if (!file.Exists())
            {
                try
                {
                    file.CreateNewFile();
                    Runtime runtime = Runtime.GetRuntime();
                    runtime.Exec("chmod 0666 " + file);
                }
                catch (Java.Lang.Exception ex)
                {
                    ex.PrintStackTrace();
                }
            }
            try
            {
                fileOutputStream = new FileOutputStream(file);
                fileOutputStream.Write(Encoding.ASCII.GetBytes(data));
            }
            catch (Java.Lang.Exception e)
            {
                e.PrintStackTrace();
            }
            finally
            {
                try
                {
                    fileOutputStream.Close();
                }
                catch (Java.Lang.Exception e)
                {
                }
            }
        }
        //==============Public methods==========//

        public void LoadImageFromFile(string imgFile, bool isNeedToCrop)
        {
            using (var jFile = new Java.IO.File(imgFile))
            {
                if (jFile.Exists())
                {
                    RequestCreator requestCreator = Picasso.With(Context)
                                                    .Load(jFile)
                                                    .Placeholder(null);

                    if (isNeedToCrop)
                    {
                        requestCreator.Fit().CenterCrop();
                    }

                    requestCreator.Into(this);
                }
            }
        }
Esempio n. 19
0
        private void delete_pic_if_needed_throw(Android.Graphics.Bitmap bit)
        {
            gThrow.Click += delegate
            {
                Java.IO.File fis = new Java.IO.File(absolut_path_pic);


                if (fis.Exists())
                {
                    fis.Delete();
                }

                Intent intent = new Intent(this, typeof(CameraSurface));

                StartActivity(intent);

                Finish();
            };
        }
Esempio n. 20
0
        public string SafeHTMLToPDF(string html, string filename, int flag)
        {
            int width  = 0;
            int height = 0;

            Android.Webkit.WebView webpage = null;
            var dir  = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/KegIdFiles/");
            var file = new Java.IO.File(dir + "/" + filename + ".pdf");

            if (!dir.Exists())
            {
                dir.Mkdirs();
            }

            int x = 0;

            while (file.Exists())
            {
                x++;
                file = new Java.IO.File(dir + "/" + filename + "( " + x + " )" + ".pdf");
            }

            if (webpage == null)
            {
                webpage = new Android.Webkit.WebView(CrossCurrentActivity.Current.AppContext);
            }

            if (flag == 0)
            {
                width  = 2959;
                height = 3873;
            }
            else
            {
                width  = 3659;
                height = 4573;
            }
            webpage.Layout(0, 0, width, height);
            webpage.LoadDataWithBaseURL("", html, "text/html", "UTF-8", null);
            webpage.SetWebViewClient(new WebViewCallBack(file.ToString(), flag));

            return(file.ToString());
        }
Esempio n. 21
0
        private string Compress(string path)
        {
            var photoUri = Android.Net.Uri.Parse(path);

            FileDescriptor fileDescriptor = null;
            Bitmap         btmp           = null;

            System.IO.FileStream stream = null;
            try
            {
                fileDescriptor = ContentResolver.OpenFileDescriptor(photoUri, "r").FileDescriptor;
                btmp           = BitmapUtils.DecodeSampledBitmapFromDescriptor(fileDescriptor, 1600, 1600);
                btmp           = BitmapUtils.RotateImageIfRequired(btmp, fileDescriptor, path);

                var directoryPictures = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
                var directory         = new Java.IO.File(directoryPictures, Constants.Steepshot);
                if (!directory.Exists())
                {
                    directory.Mkdirs();
                }

                path   = $"{directory}/{Guid.NewGuid()}.jpeg";
                stream = new System.IO.FileStream(path, System.IO.FileMode.Create);
                btmp.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);

                return(path);
            }
            catch (Exception ex)
            {
                _postButton.Enabled = false;
                this.ShowAlert(Localization.Errors.UnknownCriticalError);
                AppSettings.Reporter.SendCrash(ex);
            }
            finally
            {
                fileDescriptor?.Dispose();
                btmp?.Recycle();
                btmp?.Dispose();
                stream?.Dispose();
            }
            return(path);
        }
Esempio n. 22
0
        private void writeInStorage(String fileName, String TEXT)
        {
            bool    test;
            Context sContext = Android.App.Application.Context;

            try
            {
                Java.IO.File dirv = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath + "/AndroidTest/" + fileName + ".txt");
                Java.IO.File path = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath + "/AndroidTest");;
                if (!path.Exists())
                {
                    path.Mkdirs();
                }
                //Java.IO.File dirv = new Java.IO.File("/storage/emulated/AndroidTest");
                if (!dirv.Exists())//工作目录是否存在?
                {
                    test = dirv.CreateNewFile();
                }

                FileStream fileOS = new FileStream(dirv.ToString(), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                //String str = "this is a test about Write SD card file";
                Java.IO.BufferedWriter buf1 = new Java.IO.BufferedWriter(new Java.IO.OutputStreamWriter(fileOS));
                buf1.Write(TEXT, 0, TEXT.Length);
                buf1.Flush();
                buf1.Close();
                fileOS.Close();

                Toast.MakeText(sContext, "写入完成", ToastLength.Short).Show();
            }
            catch (Java.IO.FileNotFoundException e)
            {
                Toast.MakeText(sContext, e.ToString(), ToastLength.Short).Show();
            }
            catch (UnsupportedEncodingException e)
            {
                Toast.MakeText(sContext, e.ToString(), ToastLength.Short).Show();
            }
            catch (Java.IO.IOException e)
            {
                Toast.MakeText(sContext, e.ToString(), ToastLength.Short).Show();
            }
        }
Esempio n. 23
0
        public void InstallApp(Java.IO.File mApkFile, Context context)
        {
            bool isInstallPermission = false;//是否有8.0安装权限


            var xx = downLoadMangerIsEnable(context);

            //if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            //{
            //    isInstallPermission = getPackageManager().canRequestPackageInstalls();
            //}

            //   var mApkFile = new Java.IO.File(filename);

            Android.Net.Uri mUri = null;

            if (mApkFile.Exists())
            {
                Intent installApkIntent = new Intent(Intent.ActionView);

                installApkIntent.AddFlags(ActivityFlags.NewTask);
                installApkIntent.SetAction(Intent.ActionView);

                installApkIntent.AddFlags(ActivityFlags.GrantPersistableUriPermission
                                          | ActivityFlags.GrantReadUriPermission
                                          | ActivityFlags.GrantWriteUriPermission);

                if (Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.N)
                {
                    mUri = FileProvider.GetUriForFile(context, activity.PackageName + ".fileprovider", mApkFile);

                    //installApkIntent.SetDataAndType(mUri, "application/vnd.android.package-archive");
                    //activity.StartActivity(installApkIntent);
                }
                else
                {
                    mUri = Android.Net.Uri.FromFile(mApkFile);
                }
                installApkIntent.SetDataAndType(mUri, "application/vnd.android.package-archive");
                context.StartActivity(installApkIntent);
            }
        }
        public async void OpenFile(FileData fileToOpen)
        {
            File myFile = new File(
                Application.Context.GetExternalFilesDir(
                    Android.OS.Environment.DirectoryDocuments),
                fileToOpen.FileName);

            if (!myFile.Exists())
            {
                string pathToFile = await this.SaveFileAsync(fileToOpen)
                                    .ConfigureAwait(true);

                if (string.IsNullOrEmpty(pathToFile))
                {
                    return;
                }
            }

            this.OpenFile(myFile.Path);
        }
Esempio n. 25
0
        private async void WriteFileToCache(string url, byte[] data, int position)
        {
            byte[] imageData = data;
            using (Java.IO.File file = new Java.IO.File(GetCacheDirectory(), GetFileName(url)))
            {
                if (file.Exists())
                {
                    UpdateRecyclerView(position, file.Path);
                }
                else
                {
                    using (FileOutputStream fos = new FileOutputStream(file.Path))
                    {
                        await fos.WriteAsync(imageData);

                        UpdateRecyclerView(position, file.Path);
                    }
                }
            }
        }
Esempio n. 26
0
        private string SaveFileTemp(Bitmap btmp, string pathToExif)
        {
            FileStream stream = null;

            try
            {
                var directory = new Java.IO.File(Context.CacheDir, Constants.Steepshot);
                if (!directory.Exists())
                {
                    directory.Mkdirs();
                }

                var path = $"{directory}/{Guid.NewGuid()}.jpeg";
                stream = new FileStream(path, FileMode.Create);
                btmp.Compress(Bitmap.CompressFormat.Jpeg, 99, stream);

                var options = new Dictionary <string, string>
                {
                    { ExifInterface.TagImageLength, btmp.Height.ToString() },
                    { ExifInterface.TagImageWidth, btmp.Width.ToString() },
                    { ExifInterface.TagOrientation, "1" },
                };

                BitmapUtils.CopyExif(pathToExif, path, options);

                return(path);
            }
            catch (Exception ex)
            {
                _postButton.Enabled = false;
                Context.ShowAlert(LocalizationKeys.UnexpectedError);
                AppSettings.Reporter.SendCrash(ex);
            }
            finally
            {
                btmp?.Recycle();
                btmp?.Dispose();
                stream?.Dispose();
            }
            return(string.Empty);
        }
Esempio n. 27
0
        public void Run()
        {
            //The path where we expect the node project to be at runtime.
            var nodeDir = context.FilesDir.AbsolutePath + "/nodejs-project";

            if (WasAPKUpdated())
            {
                //Recursively delete any existing nodejs-project.
                var nodeDirReference = new Java.IO.File(nodeDir);
                if (nodeDirReference.Exists())
                {
                    DeleteFolderRecursively(new File(nodeDir));
                }
                //Copy the node project from assets into the application's data path.
                copyAssetFolder(context.ApplicationContext.Assets, "nodejs-project", nodeDir);

                saveLastUpdateTime();
            }

            CLib.StartNodeWithArguments(2, new String[] { "node", nodeDir + "/main.js" });
        }
        private static Java.IO.File PegarArquivoImagem()
        {
            Java.IO.File arquivoImagem;
            //Diretorio aonde vai ficar salvo as imagems
            Java.IO.File diretorio = new Java.IO.File(
                Android.OS.Environment.GetExternalStoragePublicDirectory(
                    Android.OS.Environment.DirectoryPictures), "Imagens");

            //Verificar se o diretorio existe
            if (!diretorio.Exists())
            {
                //é criado toda a estrutura de pais das pastas
                diretorio.Mkdirs();
            }

            //diretorio é usado aqui tb para ser a base
            //aonde a imagem Minhafoto.jpg será gravada
            arquivoImagem =
                new Java.IO.File(diretorio, "MinhaFoto.jpg");
            return(arquivoImagem);
        }
        private string GetImagePath(string newpath)
        {
            Java.IO.File file    = new Java.IO.File(new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(""), Application.Context.PackageName), "cach");
            Java.IO.File newFile = new Java.IO.File(file, newpath);

            if (!newFile.Exists())
            {
                if (!newFile.Mkdirs())
                {
                    return(null);
                }
                try
                {
                    new Java.IO.File(newFile, ".nomedia").CreateNewFile();
                }
                catch (Java.IO.IOException)
                {
                }
            }
            return(newFile.Path);
        }
Esempio n. 30
0
 /// <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 async Task <bool> SaveFile(FileData fileToSave)
        {
            try {
                var myFile = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory, fileToSave.FileName);

                if (myFile.Exists())
                {
                    return(true);
                }

                var fos = new FileOutputStream(myFile.Path);

                fos.Write(fileToSave.DataArray);
                fos.Close();

                return(true);
            } catch (Exception ex) {
                Debug.WriteLine(ex.Message);
                return(false);
            }
        }
Esempio n. 32
0
        void the_proper_save(Android.Graphics.Bitmap bit)
        {
            Java.IO.File fil = new Java.IO.File(path_file);

            if (!fil.Exists())
            {
                fil.Mkdir();
            }

            string cur_time_milisec = System.DateTime.Now.Millisecond.ToString();
            string cur_time_sec     = System.DateTime.Now.Second.ToString();

            File ceva = new Java.IO.File(path_file, "image" + cur_time_milisec + cur_time_sec + ".jpg");

            if (!ceva.Exists())
            {
                ceva.CreateNewFile();
            }


            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            bit.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
            byte[] byte_array = stream.ToArray();

            if (ceva != null)
            {
                FileOutputStream outstream = new FileOutputStream(ceva);


                outstream.Write(byte_array);
                outstream.Flush();
                outstream.Close();
            }

            Intent intent = new Intent(this, typeof(CameraSurface));

            StartActivity(intent);

            Finish();
        }
        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配置参数

            //自定义缓存路径
            var          cachePath = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/" + "eldyoungCommCenter/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
        }
        private void Save(string windowname)
        {
            if (windowname != "")
            {
                try
                {
                    Java.IO.File path = new Java.IO.File(App._dir, windowname);
                    if (!path.Exists())
                    {
                        path.Mkdirs();
                    }
                    else
                    {
                        MessageBox.Confirm(this, "警告", "该文件夹已存在,是否覆盖?", delegate
                        {
                            path.Mkdirs();
                        }, delegate { });
                    }

                    SavePics(path.ToString());

                    SaveResult.SaveGeologicalData(path.ToString());

                    SaveResult.SaveGeometricalData(path.ToString());

                    SaveResult.SaveStatisticalResult(path.ToString());

                    MessageBox.Show(this, "成功", "保存成功");
                }
                catch
                {
                    MessageBox.Show(this, "失败", "保存失败");
                }
            }
            else
            {
                MessageBox.Show(this, "注意", "测窗名称不能为空!");
            }
        }
Esempio n. 35
0
        public static List <IDictionary <string, object> > ReadFileName()
        {
            List <IDictionary <string, object> > map = new List <IDictionary <string, object> >();

            Java.IO.File file = new Java.IO.File(PATH);
            if (file.Exists())
            {
                Java.IO.File[] files = file.ListFiles();
                for (int k = 0; k < files.Length; k++)
                {
                    JavaDictionary <string, object> map2 = new JavaDictionary <string, object>();
                    ///   String str1=files[k].getAbsolutePath();
                    //  String str2=files[k].getPath();

                    map2.Add("fname", files[k].Name);
                    map2.Add("fpath", files[k].AbsolutePath);
                    map.Add(map2);
                }
                return(map);
            }
            return(map);
        }
        private void SavePDF(string fileName, MemoryStream stream)
        {
            var root = Android.OS.Environment.IsExternalStorageEmulated
                ? Android.OS.Environment.ExternalStorageDirectory.ToString()
                : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var myDir = new Java.IO.File(root + "/Chart");

            myDir.Mkdir();

            if (file != null && file.Exists())
            {
                file.Delete();
            }

            file = new Java.IO.File(myDir, fileName);

            try
            {
                var outs = new FileOutputStream(file);
                outs.Write(stream.ToArray());
                outs.Flush();
                outs.Close();
            }
            catch (Exception) {}

            if (!file.Exists())
            {
                return;
            }

            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.ActionView);

            intent.SetDataAndType(path, mimeType);
            MainActivity.Activity.StartActivity(Intent.CreateChooser(intent, "Choose App"));
        }
Esempio n. 37
0
      protected override void OnCreate(Bundle bundle)
      {
          sdCard    = Android.OS.Environment.ExternalStorageDirectory;
          directory = new Java.IO.File(sdCard.AbsolutePath + "/downloads");
          if (!directory.Exists())
          {
              directory.Mkdirs();
          }
          file = new Java.IO.File(directory, "text.txt");


          base.OnCreate(bundle);
          // Set our view from the "main" layout resource
          SetContentView(Resource.Layout.Main);
          this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
          if (bundle != null)
          {
              this.ActionBar.SelectTab(this.ActionBar.GetTabAt(bundle.GetInt("tab")));
          }

          ISharedPreferences       prefs  = ApplicationContext.GetSharedPreferences("shared", FileCreationMode.WorldReadable);
          ISharedPreferencesEditor editor = prefs.Edit();

          editor.PutString("number_of_times_accessed", "123");
          editor.Apply();

          Contact  contact   = new Contact();
          Fragment allPeople = new AllPeopleFragement(contact);

          AddTab("All people", Resource.Drawable.Icon, allPeople);
          Fragment favorite = new FavoriteFragement(contact);

          AddTab("Favorite", Resource.Drawable.Icon, favorite);
//			Overr
          //file function may be used later
//			file.Delete();
//			Fake_data ();
//			Read_file ();
      }
    //Method to save document as a file in Android and view the saved document
    public async Task SaveAndView(string fileName, String contentType, MemoryStream stream)
    {
        string root = null;

        //Get the root path in android device.
        if (Android.OS.Environment.IsExternalStorageEmulated)
        {
            root = Android.OS.Environment.ExternalStorageDirectory.ToString();
        }
        else
        {
            root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        }

        //Create directory and file
        Java.IO.File myDir = new Java.IO.File(root + "/exports");
        myDir.Mkdir();

        Java.IO.File file = new Java.IO.File(myDir, fileName);


        int increment = 2;

        //Remove if the file exists
        while (file.Exists())
        {
            string exportName = $"{DateTime.Now.Year}{DateTime.Now.Month}{DateTime.Now.Day}Export{increment}.xlsx";
            file       = new Java.IO.File(myDir, exportName);
            increment += 1;
        }

        //Write the stream into the file
        FileOutputStream outs = new FileOutputStream(file);

        outs.Write(stream.ToArray());

        outs.Flush();
        outs.Close();
    }
		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

		}
Esempio n. 40
0
		private void SetPicToLocalAndServer(Bitmap mBitmap) 
		{

			var sdStatus = Android.OS.Environment.ExternalStorageState;
			//检测sd是否可用
			if (!sdStatus.Equals (Android.OS.Environment.MediaMounted)) {
				return;
			}
			System.IO.FileStream MyFileStream = null;

			Java.IO.File file = new Java.IO.File(path);
			if(!file.Exists())
				file.Mkdirs();// 创建文件夹
			string fileName = path + "myHead.jpg";
			try{
				MyFileStream = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate);  
				//保存照片  
				mBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, MyFileStream); 

				byte[] buffer = new byte[MyFileStream.Length];
				// 设置当前流的位置为流的开始
				MyFileStream.Seek(0, SeekOrigin.Begin);
				MyFileStream.Read(buffer, 0, buffer.Length);


				var  headimgStr = Convert.ToBase64String(buffer);
				//调用restapi提交头像
				var headImgPostParam = new HeadImgPostParam () {
					UId = Global.MyInfo.UId,ImageStr = headimgStr
				};
				SetRestRequestParams (headImgPostParam);
				var restSharpRequestHelp = new RestSharpRequestHelp(headImgPostParam.Url,requestParams);
				restSharpRequestHelp.ExcuteAsync ((RestSharp.IRestResponse response) => {
					if(response.ResponseStatus == RestSharp.ResponseStatus.Completed && response.StatusCode == System.Net.HttpStatusCode.OK)
					{
						//获取并解析返回resultJson获取安全码结果值
						var result = response.Content;
						var headimgJson = JsonConvert.DeserializeObject<HeadImgJson>(result);
						if(headimgJson.statuscode == "1")
							Global.MyInfo.HeadImgUrl = headimgJson.data[0].HeadImgUrl;
						else
						{
							Activity.RunOnUiThread(()=>
								{
									Toast.MakeText(Activity,"头像上传失败",ToastLength.Short).Show();
								});
						}

					}
	
				});
			}
			catch(Java.IO.FileNotFoundException e) {
				e.PrintStackTrace ();
			}
			finally {
				MyFileStream.Flush ();
				MyFileStream.Close ();
			}	

		}
        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);
            }
        }
		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;
			}
		}
Esempio n. 43
0
 /// <summary>
 /// Does a file with given path exist on the filesystem?
 /// </summary>
 public static bool Exists(string path)
 {
     var file = new JFile(path);
     return file.IsFile && file.Exists();
 }
Esempio n. 44
0
		/// <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 ();
		}
Esempio n. 45
0
		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);

		}
		//--->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;
		}
Esempio n. 47
0
		//***************************************************************************************************
		//******************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));

		}
Esempio n. 48
0
		async private void UploadPicture()
		{
			if (string.IsNullOrEmpty(PictureFilePath) || UploadAttemped)
			{
				return;
			}

			Java.IO.File imageFile = new Java.IO.File(PictureFilePath);
			if (!imageFile.Exists())
			{
				return;
			}

			ProgressDialog progress = new ProgressDialog(Activity);
			progress.Indeterminate = true;
			progress.SetProgressStyle(ProgressDialogStyle.Spinner);
			progress.SetMessage(Strings.posting);
			progress.SetCancelable(false);
			progress.Show();

			try
			{
				Bitmap SelectedImage = BitmapFactory.DecodeFile(imageFile.AbsolutePath);
				if (SelectedImage == null)
				{
					return;
				}
				SelectedImage = ImageUtils.ReduceSizeIfNeededByWidth(SelectedImage, 1000);
				SelectedImage = ImageUtils.RotateImageIfNeeded(SelectedImage, imageFile.AbsolutePath);
				System.Byte[] myByteArray = null;
				System.IO.MemoryStream stream = new System.IO.MemoryStream();
				SelectedImage.Compress(Bitmap.CompressFormat.Jpeg, 80, stream);
				myByteArray = stream.ToArray();

				UploadAttemped = true;
				Post result = await TenServices.Post("", myByteArray);

				progress.Dismiss();

				if (result != null)
				{
					FeedUtils.PassPostToAllFeedsIfExistsWithInclude(result, FeedTypeEnum.FeedType.HomeFeed);

					Activity.SetResult(Result.Ok);
					Activity.Finish();
				}
			}
			catch (RESTError error)
			{
				progress.Dismiss();
				System.Console.WriteLine(error.Message);
				UploadAttemped = false;
			}
		}
Esempio n. 49
0
        /// <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;
        }
Esempio n. 50
0
        public override void OnCreate()
        {
            base.OnCreate ();

                AndroidEnvironment.UnhandledExceptionRaiser += MyApp_UnhandledExceptionHandler;

                TapGlobal tapglobal = new TapGlobal (this);
                taputil= new TapUtil (this);
                GlobalVariable staticvalue = new GlobalVariable ();
                networknamager = new NetworkManager ();
                imagemanager = new ImageManager ();
                debugreport = new DebugReport (this);

                string databasename="tap5050seller.db";
                string path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Tap5050/";
                Java.IO.File basefile = new Java.IO.File (global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath+"/Tap5050/");

                Java.IO.File internalbasefile = new Java.IO.File (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal));
                string appinternalpath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
                var personalpath=appinternalpath+databasename;

                bool success = true;
                if (!internalbasefile.Exists()){
                    success=internalbasefile.Mkdirs();
                    Java.IO.File file =new Java.IO.File(personalpath);
                    file.CreateNewFile ();
                }

                if (success){
                    databasemanager = new DatabaseManager (personalpath);
                }

                INSTANCE = this;
        }
Esempio n. 51
0
			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;
				}

			}
Esempio n. 52
0
        private async Task<string> CopyAssets ()
        {
            try {
                Android.Content.Res.AssetManager assetManager = _context.Assets;
                string[] files = assetManager.List ("tessdata");
                File file = _context.GetExternalFilesDir (null);
                var tessdata = new File (_context.GetExternalFilesDir (null), "tessdata");
                if (!tessdata.Exists ()) {
                    tessdata.Mkdir ();
                } else {
                    var packageInfo = _context.PackageManager.GetPackageInfo (_context.PackageName, 0);
                    var version = packageInfo.VersionName;
                    var versionFile = new File (tessdata, "version");
                    if (versionFile.Exists ()) {
                        var fileVersion = System.IO.File.ReadAllText (versionFile.AbsolutePath);
                        if (version == fileVersion) {
                            Log.Debug ("[TesseractApi]", "Application version didn't change, skipping copying assets");
                            return file.AbsolutePath;
                        }
                        versionFile.Delete ();
                    }
                    System.IO.File.WriteAllText (versionFile.AbsolutePath, version);
                }

                Log.Debug ("[TesseractApi]", "Copy assets to " + file.AbsolutePath);

                foreach (var filename in files) {
                    using (var inStream = assetManager.Open ("tessdata/" + filename)) {
                        var outFile = new File (tessdata, filename);
                        if (outFile.Exists ()) {
                            outFile.Delete ();
                        }
                        using (var outStream = new FileStream (outFile.AbsolutePath, FileMode.Create)) {
                            await inStream.CopyToAsync (outStream);
                            await outStream.FlushAsync ();
                        }
                    }
                }
                return file.AbsolutePath;
            } catch (Exception ex) {
                Log.Error ("[TesseractApi]", ex.Message);
            }
            return null;
        }
Esempio n. 53
0
 /// <summary>
 /// Read a file with given path and return a string with it's entire contents.
 /// </summary>
 public static string ReadAllText(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 FileReader(file);
     try
     {
         var array = new char[4096];
         var buffer = new StringBuffer();
         int len;
         while ((len = reader.Read(array, 0, array.Length)) > 0)
         {
             buffer.Append(array, 0, len);
         }
         return buffer.ToString();
     }
     finally
     {
         reader.Close();
     }
 }
Esempio n. 54
0
		//Mediante este metodo verificamos si existe en directorio para guardar las fotografias en caso de no existir lo creamos
		private void CreateDirectoryForPictures()
		{
			_Directorio = new File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), "FacebookDemo");
			if (!_Directorio.Exists())
			{
				_Directorio.Mkdirs();
			}
		}