private void createFile(string filename, Java.IO.File extStore)
        {
            Java.IO.File file = new Java.IO.File(extStore + "/" + filename + ".aes");

            if (filename.IndexOf(".") != -1)
            {
                try
                {
                    file.CreateNewFile();
                }
                catch (Java.IO.IOException e)
                {
                    // TODO Auto-generated catch block
                    Android.Util.Log.Error("lv", e.Message);
                }
                Android.Util.Log.Error("lv", "file created");
            }
            else
            {
                file.Mkdir();
                Android.Util.Log.Error("lv", "folder created");
            }

            file.Mkdirs();
        }
Пример #2
0
        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 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            }

            //Create directory and file
            Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion");
            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);

                var emailMessanger = CrossMessaging.Current.EmailMessenger;
                if (emailMessanger.CanSendEmail)
                {
                    var email = new EmailMessageBuilder()
                                .To("*****@*****.**")
                                .Subject("Punches")
                                .Body("Test Run")
                                .WithAttachment(file)
                                .Build();

                    emailMessanger.SendEmail(email);
                }


                //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"));
            }
        }
Пример #3
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();
            }
        }
Пример #4
0
        public bool savelocal()
        {
            try
            {
                if (Android.OS.Environment.ExternalStorageState.Equals(Android.OS.Environment.MediaMounted))
                {
                    Java.IO.File dir = new Java.IO.File(SavePath);
                    if (!dir.Exists())
                    {
                        dir.Mkdir();
                    }

                    HttpURLConnection connection = (HttpURLConnection)mURL.OpenConnection();
                    connection.RequestMethod = "GET";
                    connection.ReadTimeout   = 5000;
                    Stream       inStream = connection.InputStream;
                    StreamReader reader   = new StreamReader(inStream);
                    StreamWriter writer   = new StreamWriter(SavePath + savename);
                    writer.Write(reader.ReadToEnd());
                    writer.Flush();
                    reader.Close();
                    writer.Close();
                    return(true);
                }
                return(false);
            }
            catch (Exception)
            {
                return(false);

                throw;
            }
        }
        public async Task Save(string filename, string contentType, MemoryStream stream)
        {
            var root = "";

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

            var myDir  = new Java.IO.File(root + "/Kişisel Takip");
            var result = myDir.Mkdir();
            //Directory.CreateDirectory(myDir.Path);
            var file = new Java.IO.File(myDir, filename);

            //if (file.Exists()) file.Delete();

            var outs = new FileOutputStream(file);

            outs.Write(stream.ToArray());

            outs.Flush();
            outs.Close();
        }
    public async Task <string> SaveAsync(byte[] fileData, DataFileDialogModel dataFileDialog)
    {
        try
        {
            await Task.Run(() =>
            {
                string filePath    = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, DefaultDir);
                Java.IO.File myDir = new Java.IO.File(filePath);
                if (!myDir.Exists())
                {
                    myDir.Mkdir();
                }
                string fullName = Path.Combine(filePath, dataFileDialog.DefaultFileName + dataFileDialog.FileType);
                if (System.IO.File.Exists(fullName))
                {
                    System.IO.File.Delete(fullName);
                }
                System.IO.File.WriteAllBytes(fullName, fileData);
            });

            return($"Файл сохранен в папку {DefaultDir}");
        }
        catch (Exception)
        {
            return("Ошибка сохранения файла");
        }
    }
Пример #7
0
        public async Task View(Stream stream, string filename)
        {
            if ((int)Android.OS.Build.VERSION.SdkInt >= 23)
            {
                bool result = await PermissionsHelper.RequestStorrageAccess();

                if (!result)
                {
                    return;
                }
            }

            string root = null;

            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.App.Application.Context.GetExternalFilesDir(null).ToString();
            }
            else
            {
                root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }

            Java.IO.File myDir = new Java.IO.File(root + "/Telerik");
            myDir.Mkdir();
            Java.IO.File file = new Java.IO.File(myDir, filename);

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

            using (FileOutputStream outs = new FileOutputStream(file))
            {
                stream.Seek(0, SeekOrigin.Begin);
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                outs.Write(buffer);
            }

            if (file.Exists())
            {
                var             context = Android.App.Application.Context;
                Android.Net.Uri path    = AndroidX.Core.Content.FileProvider.GetUriForFile(context, "SDKBrowser.Android.fileprovider", 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);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);

                var chooser = Intent.CreateChooser(intent, "Choose App");
                chooser.SetFlags(ActivityFlags.NewTask);
                chooser.AddFlags(ActivityFlags.GrantReadUriPermission);
                context.StartActivity(chooser);
            }

            return;
        }
Пример #8
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));
        }
        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 + "/DocScan");
                myDir.Mkdir();
                Java.IO.File myDir1 = new Java.IO.File(root + "/DocScan/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");
                //
            }
        }
Пример #10
0
        public void Save(string filename, string contentType, MemoryStream stream)
        {
            string exception = string.Empty;
            string root      = null;


            if (ContextCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
            {
                ActivityCompat.RequestPermissions((Android.App.Activity)Forms.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
            }

            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(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"));
                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);
                Android.Net.Uri path = FileProvider.GetUriForFile(Forms.Context, Android.App.Application.Context.PackageName + ".provider", file);
                intent.SetDataAndType(path, mimeType);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
            }
        }
Пример #11
0
    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"));
         * }*/
    }
Пример #12
0
        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));
                }
            }
        }
Пример #13
0
        /// <summary>
        /// Used to save a Exporting grid to Excel and PDF file in Android devices from Interface of ISAVE
        /// </summary>
        /// <param name="fileName">string type of filename parameter</param>
        /// <param name="contentType">string type of contentType parameter</param>
        /// <param name="stream">MemoryStream type of stream parameter</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();
            }

            if (file.Exists() && contentType != "application/html")
            {
                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);

                //// Forms.Context is obsolete, Hence used local context

                Android.Net.Uri path = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file);
                intent.SetDataAndType(path, mimeType);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                Intent chooserIntent = Intent.CreateChooser(intent, "Open With");
                chooserIntent.AddFlags(ActivityFlags.NewTask);
                Android.App.Application.Context.StartActivity(chooserIntent);
            }
        }
        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.SetDataAndType(path, mimeType);
                Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
            }
        }
Пример #15
0
    //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;

        if (ContextCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
        {
            ActivityCompat.RequestPermissions((Android.App.Activity)Forms.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
        }

        //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 + "/Syncfusion");
        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())
        {
            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);
            Android.Net.Uri path = FileProvider.GetUriForFile(Forms.Context, Android.App.Application.Context.PackageName + ".provider", file);
            intent.SetDataAndType(path, mimeType);
            intent.AddFlags(ActivityFlags.GrantReadUriPermission);
            Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
        }
    }
Пример #16
0
        public void Print(string fileName, string contentType, MemoryStream stream)
        {
            string root;

            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}/Atas");
            myDir.Mkdir();

            Java.IO.File file = new Java.IO.File(myDir, fileName);
            if (file.Exists())
            {
                file.Delete();
            }

            try
            {
                FileOutputStream outs = new FileOutputStream(file);
                stream.Position = 0;
                outs.Write(stream.ToArray());
                outs.Flush();
                outs.Close();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Print error: {e.ToString()}");
            }
            finally
            {
                stream.Dispose();
            }

            if (file.Exists())
            {
                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);
                var    contentUri = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".fileprovider", file);
                intent.SetDataAndType(contentUri, mimeType);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                intent.AddFlags(ActivityFlags.NewTask);
                intent.AddFlags(ActivityFlags.ClearTop);
                MainActivity.Instance.StartActivity(intent);
            }
        }
Пример #17
0
        private void Overflow_provider_ShareTargetSelected(object sender, ShareActionProvider.ShareTargetSelectedEventArgs e)
        {
            File folder = new File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Download/1C_Files/");

            if (folder.Exists() == false)
            {
                folder.Mkdir();
            }

            using (StreamWriter write = new StreamWriter(mReportAddr, false, Encoding.UTF8))
            {
                write.Write(html);
            }
        }
Пример #18
0
        public bool UnzipFiles(string path, string zipname)
        {
            var f = new Java.IO.File(path);

            if (!f.Exists())
            {
                f.Mkdir();
            }
            try
            {
                String filename;
                var    inputstream = System.IO.File.Open(Path.Combine(path, zipname + ".zip"), FileMode.Open);
                var    zis         = new Java.Util.Zip.ZipInputStream(inputstream);
                Java.Util.Zip.ZipEntry ze;
                byte[] buffer = new byte[1024];
                int    count;

                while ((ze = zis.NextEntry) != null)
                {
                    filename = ze.Name;
                    // Need to create directories if not exists, or
                    // it will generate an Exception...
                    if (ze.IsDirectory)
                    {
                        Java.IO.File fmd = new Java.IO.File(Path.Combine(Path.Combine(path, zipname), filename));
                        fmd.Mkdirs();
                        continue;
                    }

                    var fout = new Java.IO.FileOutputStream(Path.Combine(Path.Combine(path, zipname), filename));
                    while ((count = zis.Read(buffer)) != -1)
                    {
                        fout.Write(buffer, 0, count);
                    }

                    fout.Close();
                    zis.CloseEntry();
                }

                zis.Close();
            }
            catch (Java.IO.IOException iox)
            {
                System.Console.WriteLine(iox.Message);
                return(false);
            }

            return(true);
        }
Пример #19
0
    //Method to save document as a file in Android and view the saved document
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
    public async Task SaveAndView(string fileName, String contentType, MemoryStream stream)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
    {
        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);
        }
        string documentsPath = Environment.CurrentDirectory;

        //Create directory and file
        Application.Current.Properties["savename"] = root + "/GreenBankX";
        Java.IO.File myDir = new Java.IO.File(root + "/GreenBankX");
        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"));
        }
    }
Пример #20
0
        public void Save(string fileName, String contentType, MemoryStream stream, Context context)
        {
            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 + "/PocketStatistician");
            myDir.Mkdir();

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

            int fileIndent = 1;

            while (file.Exists())
            {
                string newFileName = string.Concat(fileName, fileIndent, ".xlsx");
                file = new Java.IO.File(myDir, newFileName);
                fileIndent++;
            }

            try
            {
                FileOutputStream outs = new FileOutputStream(file, false);
                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(exception);
                Toast.MakeText(this, "Table successfully exported!", ToastLength.Short).Show();
            }
        }
Пример #21
0
    //Method to save document as a file in Android and view the saved document
    public string 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 + "/Syncfusion");
        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();
        Android.Net.Uri path = null;
        //Invoke the created file for viewing
        if (file.Exists())
        {
            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, "Elija una aplicación"));*/
        }

        return(path.Path);
    }
Пример #22
0
        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);
        }
Пример #23
0
        //Method to save document as a file in Android and view the saved document
        public void SaveAndView(string fileName, String contentType, MemoryStream stream, Akcje activity)
        {
            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 + "/Syncfusion");
            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.AddFlags(ActivityFlags.NewTask);
                intent.SetDataAndType(path, mimeType);
                //intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                activity.StartActivity(Intent.CreateChooser(intent, "Choose App"));
            }
        }
Пример #24
0
        private void CreateImageFile(string timeStamp)
        {
            newfile = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(
                                           Android.OS.Environment.DirectoryPictures), "cfw" + timeStamp + ".jpg");
            mCurrentPhotoPath = newfile.AbsolutePath;
            if (!newfile.Exists())
            {
                newfile.Mkdir();
                if (!newfile.Exists())
                {
                    throw new Exception("FIle error!");
                }
            }
            bool setWritable = false;

            setWritable = newfile.SetWritable(true, false);
        }
Пример #25
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);
        }
Пример #26
0
        //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 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            }

            //Create directory and file
            Java.IO.File myDir = new Java.IO.File(root + "/FinantialCount");
            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.AddFlags(ActivityFlags.NewTask);
                intent.SetDataAndType(path, mimeType);
            }
        }
Пример #27
0
    //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 (OSEnvironment.IsExternalStorageEmulated)
        {
            root = OSEnvironment.ExternalStorageDirectory.ToString();
        }
        else
        {
            root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        }

        //Create directory and file
        Java.IO.File myDir = new Java.IO.File(root + "/Owner");
        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())
        {
            Uri    path      = Uri.FromFile(file);
            string extension = MimeTypeMap.GetFileExtensionFromUrl(Uri.FromFile(file).ToString());
            string mimeType  = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
            Intent intent    = new Intent(Intent.ActionView);
            intent.SetDataAndType(path, mimeType);
            Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
        }
    }
Пример #28
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 of android device.
            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
            {
                root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            }

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

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

            //Remove the file if exists.
            if (file.Exists())
            {
                file.Delete();
            }

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

            outs.Write(stream.ToArray());

            outs.Flush();
            outs.Close();

            //Launch the saved file for viewing in default viewer.
            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"));
            }
        }
        public Task View(Stream stream, string filename)
        {
            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 + "/Telerik");
            myDir.Mkdir();
            Java.IO.File file = new Java.IO.File(myDir, filename);

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

            using (FileOutputStream outs = new FileOutputStream(file))
            {
                stream.Seek(0, SeekOrigin.Begin);
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                outs.Write(buffer);
            }

            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"));
            }

            return(Task.CompletedTask);
        }
Пример #30
0
            /// <summary>
            /// 创建一个文件或文件夹并返回是否创建成功。如果文件已经存在,则直接返回false。
            /// </summary>
            /// <param name="path">路径</param>
            /// <returns></returns>
            public static bool Create(string path)
            {
                var f = new Java.IO.File(path);

                if (path.EndsWith(Java.IO.File.Separator))
                {
                    return(f.Mkdir());
                }
                else
                {
                    try
                    {
                        return(f.CreateNewFile());
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }
            }
Пример #31
0
        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"));

            }
        }
Пример #32
0
        public void Save(string fileName, string contentType, MemoryStream stream)
        {
            var    context = MainActivity.Instance;
            string root    = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            Java.IO.File myDir = new Java.IO.File(root + "/FileRepos");
            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)
            {
                _ = e.ToString();
            }

            if (file.Exists() && contentType != "application/html")
            {
                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);
                Android.Net.Uri path = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file);
                intent.SetDataAndType(path, mimeType);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);

                context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
            }
        }
Пример #33
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));

		}
Пример #34
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;
        }
Пример #35
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;
				}

			}
		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;
			}
		}
		//--->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;
		}
Пример #38
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 ();
		}