Ejemplo n.º 1
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 + ".fileprovider", file);
                intent.SetDataAndType(path, mimeType);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
            }
        }
Ejemplo n.º 2
0
        public async Task <string> ConvertHtmlToPDF(string html, string fileName)
        {
            var dir  = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Download/");
            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");
            }

            var webpage = new Android.Webkit.WebView(MainActivity.Instance);
            //var windowManager = MainActivity.Instance.GetSystemService(Android.Content.Context.WindowService);
            //DisplayMetrics outMetrics = new DisplayMetrics();
            //windowManager.DefaultDisplay.GetMetrics(outMetrics);
            //int widthPixels = outMetrics.WidthPixels;
            //int heightPixels = outMetrics.HeightPixels;

            //int width = widthPixels;
            //int height = heightPixels;
            int width  = 2102;
            int height = 2937;

            webpage.Layout(0, 0, width, height);

            var client      = new WebViewCallBack(file.ToString());
            var tokenSource = new CancellationTokenSource();
            var task        = Task.Run(() =>
            {
                if (tokenSource.Token.IsCancellationRequested)
                {
                    return;
                }
                while (true)
                {
                    if (tokenSource.Token.IsCancellationRequested)
                    {
                        break;
                    }
                }
            }, tokenSource.Token);

            client.OnPageLoadFinished += (s, e) =>
            {
                tokenSource.Cancel();
            };
            webpage.SetWebViewClient(client);
            webpage.LoadDataWithBaseURL("", html, "text/html", "UTF-8", null);

            await task;

            return(file.ToString());
        }
        public async void PutKeysButtonOnClick()
        {
            File directory;

            // Shared key list file, Please configure according to the actual situation
            if (Android.OS.Environment.ExternalStorageState == "mounted")
            {
                //create new file directory object
                directory = FilesDir;

                if (directory.Exists())
                {
                    Toast.MakeText(this, "File exist.", ToastLength.Short).Show();
                }
                string fileName = directory.ToString() + "/putkeysfile.zip";

                File file = new Java.IO.File(fileName);
                if (!file.Exists())
                {
                    file.CreateNewFile();
                }
                else
                {
                    List <File> putList = new List <File>();
                    putList.Add(file);
                    DiagnosisConfiguration diagnosisConfiguration = new DiagnosisConfiguration.Builder().Build();

                    PendingIntent pendingIntent = PendingIntent.GetService(this, 0, new Intent(this, typeof(BackgroundContactCheckingIntentService)), PendingIntentFlags.UpdateCurrent);

                    //Put shared key files to diagnosisconfiguration.
                    var   resultPutSharedKeys = mEngine.PutSharedKeyFilesAsync(pendingIntent, putList, diagnosisConfiguration, token);
                    await resultPutSharedKeys;
                    if (resultPutSharedKeys.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion))
                    {
                        Log.Debug(TAG, "PutSharedKeyFiles succeeded.");
                    }
                }
            }
        }
Ejemplo n.º 4
0
        private static async Task <Java.IO.File> SavePhotoToDiskAsync(byte[] data, string directory)
        {
            Java.IO.File pictureFile;
            string       photoFileName;

            using (var pictureFileDir = new Java.IO.File(directory))
            {
                if (!pictureFileDir.Exists() && !pictureFileDir.Mkdirs())
                {
                    _logger.LogError("Can't create directory to save image");
                    return(null);
                }

                photoFileName = $"Picture-{Guid.NewGuid().ToString()}.jpg";
                var imageFilePath = $"{pictureFileDir.Path}{Java.IO.File.Separator}{photoFileName}";
                pictureFile = new Java.IO.File(imageFilePath);
            }

            FileOutputStream fileOutputStream = null;

            try
            {
                fileOutputStream = new FileOutputStream(pictureFile);
                await fileOutputStream.WriteAsync(data);
            }
            catch (Exception e)
            {
                _logger.LogError($"File {photoFileName} has not been saved: {e.Message}", e);
            }
            finally
            {
                fileOutputStream?.Close();
                fileOutputStream?.Dispose();
            }

            return(pictureFile);
        }