示例#1
0
    public Task share(string filepath, string title)
    {
        var extension   = filepath.Substring(filepath.LastIndexOf(".") + 1).ToLower();
        var contentType = string.Empty;

        // You can manually map more ContentTypes here if you want.
        switch (extension)
        {
        case "pdf":
            contentType = "application/pdf";
            break;

        case "png":
            contentType = "image/png";
            break;

        default:
            contentType = "application/octetstream";
            break;
        }

        var intent = new Intent(Intent.ActionSend);

        intent.SetType(contentType);
        intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + filepath));
        intent.PutExtra(Intent.ExtraText, string.Empty);
        intent.PutExtra(Intent.ExtraSubject, string.Empty);

        var chooserIntent = Intent.CreateChooser(intent, title ?? string.Empty);

        chooserIntent.SetFlags(ActivityFlags.ClearTop);
        chooserIntent.SetFlags(ActivityFlags.NewTask);
        _context.StartActivity(chooserIntent);

        return(Task.FromResult(true));
    }
示例#2
0
        public Task <string> PickImageAsync()
        {
            // Define the Intent for getting images
            //Intent intent = new Intent();
            //intent.SetType("image/*");
            //intent.SetAction(Intent.ActionGetContent);

            Intent intent = new Intent(Intent.ActionPick);

            intent.SetType("image/*");
            //intent.PutExtra(Intent.ExtraAllowMultiple, false);
            intent.SetAction(Intent.ActionGetContent);

            // Start the picture-picker activity (resumes in MainActivity.cs)
            MainActivity.Current.StartActivityForResult(
                Intent.CreateChooser(intent, "Select Image"),
                MainActivity.PickImageId);

            // Save the TaskCompletionSource object as a MainActivity property
            MainActivity.Current.PickImageTaskCompletionSource = new TaskCompletionSource <string>();

            // Return Task object
            return(MainActivity.Current.PickImageTaskCompletionSource.Task);
        }
示例#3
0
        void OnMenuItemSelected(object sender, Android.Support.Design.Widget.NavigationView.NavigationItemSelectedEventArgs e)
        {
            switch (e.MenuItem.ItemId)
            {
            case Resource.Id.myProfileMain:
                Intent userIntent = new Intent(this, typeof(MyProfileActivity));
                StartActivity(userIntent);
                break;

            case Resource.Id.myGroupMain:
                Intent groupIntent = new Intent(this, typeof(MyGroupActivity));
                StartActivity(groupIntent);
                break;

            case Resource.Id.settingsMain:
                Intent optionsIntent = new Intent(this, typeof(OptionsActivity));
                StartActivity(optionsIntent); break;

            case Resource.Id.feedbackMain:
                Intent emailIntent = new Intent(Intent.ActionSendto, Uri.FromParts("mailto", "*****@*****.**", null));
                emailIntent.PutExtra(Intent.ExtraSubject, "Feedback");
                emailIntent.PutExtra(Intent.ExtraText, "Problem/Suggestion/etc.");
                StartActivity(Intent.CreateChooser(emailIntent, "Send email..."));
                break;

            case Resource.Id.logoutMain:
                StartActivity(typeof(LoginActivity));
                Finish();
                ChamberOfSecrets.Instance.group        = new Group();
                ChamberOfSecrets.Instance.LoggedUser   = new User();
                ChamberOfSecrets.Instance.AllGroceries = new AvailableGroceries();
                break;
            }

            mainDrawerLayout.CloseDrawer(GravityCompat.Start);
        }
示例#4
0
        Task <bool> PlatformOpenAsync(OpenFileRequest request)
        {
            var contentUri = FileSystemUtils.GetShareableFileUri(request.File);

            var intent = new Intent(Intent.ActionView);

            intent.SetDataAndType(contentUri, request.File.ContentType);
            intent.SetFlags(ActivityFlags.GrantReadUriPermission);

            var chooserIntent = Intent.CreateChooser(intent, request.Title ?? string.Empty);
            var flags         = ActivityFlags.ClearTop | ActivityFlags.NewTask;

#if __ANDROID_24__
            if (OperatingSystem.IsAndroidVersionAtLeast(24))
            {
                flags |= ActivityFlags.LaunchAdjacent;
            }
#endif
            chooserIntent.SetFlags(flags);

            Application.Context.StartActivity(chooserIntent);

            return(Task.FromResult(true));
        }
示例#5
0
        private void WriteToFile(string fileName, StringBuilder result)
        {
            string destination = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

            destination = Path.Combine(destination, fileName);

            //saving the file into device
            using (var writer = new StreamWriter(destination, false))
            {
                writer.Write(result.ToString());
            }

            Java.IO.File filelocation = new Java.IO.File(destination);
            var          path         = FileProvider.GetUriForFile(context, "de.stryi.exportcsv.fileprovider", filelocation);
            Intent       fileIntent   = new Intent(Intent.ActionSend);

            fileIntent.SetType("text/csv");
            fileIntent.PutExtra(Intent.ExtraSubject, fileName);
            fileIntent.SetFlags(ActivityFlags.NewTask);
            fileIntent.AddFlags(ActivityFlags.GrantReadUriPermission);

            fileIntent.PutExtra(Intent.ExtraStream, path);
            context.StartActivity(Intent.CreateChooser(fileIntent, "CSV Datei senden"));
        }
示例#6
0
        /// <summary>
        /// Sends an intent to start the FilePicker
        /// </summary>
        private void StartPicker()
        {
            var intent = new Intent(Intent.ActionGetContent);

            intent.SetType("*/*");

            string[] allowedTypes = Intent.GetStringArrayExtra(ExtraAllowedTypes)?.
                                    Where(o => !string.IsNullOrEmpty(o) && o.Contains("/")).ToArray();

            if (allowedTypes != null && allowedTypes.Any())
            {
                intent.PutExtra(Intent.ExtraMimeTypes, allowedTypes);
            }

            intent.AddCategory(Intent.CategoryOpenable);
            try
            {
                this.StartActivityForResult(Intent.CreateChooser(intent, "Select file"), 0);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
        }
        private void SendIntentToTakeVideoOrImage()
        {
            try {
                StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                StrictMode.SetVmPolicy(builder.Build());

                _takeImageOutputFile = Java.IO.File.CreateTempFile(Guid.NewGuid().ToString(), ".jpeg", new Java.IO.File(GetExternalDirPath()));

                Intent takeImageIntent = new Intent(MediaStore.ActionImageCapture);
                takeImageIntent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_takeImageOutputFile));

                Intent takeVideoIntent = new Intent(MediaStore.ActionVideoCapture);

                Intent chooserIntent = Intent.CreateChooser(takeImageIntent, "Take Image or Video with:");
                chooserIntent.PutExtra(Intent.ExtraInitialIntents, new Intent[] { takeVideoIntent });
                StartActivityForResult(chooserIntent, _TAKE_IMAGE_OR_VIDEO_REQUEST_CODE);
            }
            catch (Exception exc) {
                CompleteActionTakeVideoOrImage(new PickedMediaFromGallery()
                {
                    Exception = exc, ErrorMessage = _TAKE_VIDEO_OR_IMAGE_PREPARE_INTENT_ERROR
                });
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.connectLayout);
            call        = FindViewById <Button>(Resource.Id.callBtn);
            sms         = FindViewById <Button>(Resource.Id.smsBtn);
            email       = FindViewById <Button>(Resource.Id.emailBtn);
            input       = FindViewById <EditText>(Resource.Id.editText1);
            call.Click += Call_Click;
            call.Click += delegate
            {
                var url1   = Android.Net.Uri.Parse("tel:6477088494");
                var intent = new Intent(Intent.ActionCall, url1);
                StartActivity(intent);
            };
            sms.Click += Sms_Click;
            sms.Click += delegate
            {
                var smsUri    = Android.Net.Uri.Parse("smsto:1112223333");
                var smsIntent = new Intent(Intent.ActionSendto, smsUri);
                smsIntent.PutExtra("sms_body", input.Text);
                StartActivity(smsIntent);
            };
            email.Click += Email_Click;
            email.Click += delegate
            {
                var em = new Intent(Android.Content.Intent.ActionSend);
                em.PutExtra(Android.Content.Intent.ExtraEmail, new string[] { "*****@*****.**" });
                em.PutExtra(Android.Content.Intent.ExtraCc, new string[] { "*****@*****.**" });
                em.PutExtra(Android.Content.Intent.ExtraText, "This is extra text.");
                em.SetType("message/rfc822");
                StartActivity(Intent.CreateChooser(em, "Send"));
            };
        }
示例#9
0
        public static void StartAction(string actionType, string filePath, Context context)
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                Android.Net.Uri uriToShare = AndroidX.Core.Content.FileProvider.GetUriForFile(context,
                                                                                              "com.dotnetflow.extractr.droid.fileprovider",
                                                                                              new Java.IO.File(filePath));

                Intent intent = new Intent(actionType);

                intent.PutExtra(Intent.ExtraText, $"Sharing : { filePath.GetFileNameWithoutExtension()}");

                if (filePath.EndsWith("zip"))
                {
                    intent.SetType("application/zip");
                }
                else
                {
                    intent.SetType("application/pdf");
                }

                if (actionType == Intent.ActionSend)
                {
                    intent.PutExtra(Intent.ExtraStream, uriToShare);
                }

                if (actionType == Intent.ActionView)
                {
                    intent.SetData(uriToShare);
                }

                intent.SetFlags(ActivityFlags.GrantReadUriPermission);

                context.StartActivity(Intent.CreateChooser(intent, "EXTRACTR"));
            }
        }
        public Task <Stream> GetImageStreamAsync()
        {
            _logger.Log("GetImageStreamAsync invoked.");

            // Define the Intent for getting images
            Intent intent = new Intent();

            intent.SetType("image/*");
            intent.SetAction(Intent.ActionGetContent);

            // Get the MainActivity instance
            var activity = (MainActivity)_context;

            // Start the picture-picker activity (resumes in MainActivity.cs)
            activity.StartActivityForResult(
                Intent.CreateChooser(intent, "Select Photo"),
                MainActivity.PickImageId);

            // Save the TaskCompletionSource object as a MainActivity property
            activity.PickImageTaskCompletionSource = new TaskCompletionSource <Stream>();

            // Return Task object
            return(activity.PickImageTaskCompletionSource.Task);
        }
示例#11
0
        private void MenuHandler(object sender, SupportToolbar.MenuItemClickEventArgs e)
        {
            switch (e.Item.ItemId)
            {
            case Resource.Id.action_choose:
                Log.Info("Dictionary", "Choose");
                //TODO
                break;

            case Resource.Id.action_share:
                Log.Info("Dictionary", "Share");

                Intent intent = new Intent(Intent.ActionSend);
                intent.SetType("text/plain");

                String shareBody = "Yolo Swag Wafa";

                intent.PutExtra(Intent.ExtraSubject, "A definition by Dinky Dictionary");
                intent.PutExtra(Intent.ExtraText, shareBody);

                StartActivity(Intent.CreateChooser(intent, "Share via"));
                break;
            }
        }
 private AlertDialog.Builder GetDialog()
 {
     try
     {
         var builder = new AlertDialog.Builder(this);
         builder.SetMessage(Resource.String.LicenseFailedMessageString);
         builder.SetPositiveButton(GetString(Resource.String.WriteString), delegate
         {
             try
             {
                 var emailIntent = new Intent(Intent.ActionSendto, Uri.Parse("mailto:[email protected]"));
                 emailIntent.PutExtra(Intent.ExtraSubject, "Ошибка лицензии");
                 StartActivity(Intent.CreateChooser(emailIntent, string.Empty));
             }
             catch (Exception exception)
             {
                 GaService.TrackAppException(this.Class, "SendEmail", exception, false);
                 var errorBuilder = new AlertDialog.Builder(this);
                 errorBuilder.SetMessage(GetString(Resource.String.SendEmailFailedHeaderString)
                                         + System.Environment.NewLine
                                         + GetString(Resource.String.SendEmailFailedString));
                 errorBuilder.SetCancelable(false);
                 errorBuilder.SetPositiveButton("Ok", (sender, args) => base.OnBackPressed());
                 errorBuilder.Show();
             }
         });
         builder.SetNegativeButton("Ok", (sender, args) => base.OnBackPressed());
         builder.SetCancelable(false);
         return(builder);
     }
     catch (Exception exception)
     {
         GaService.TrackAppException(this.Class, "GetDialog", exception, false);
         throw;
     }
 }
        public Task <Stream> GetImageStreamAsync()
        {
            // Define the Intent for getting images
            Intent intent = new Intent();

            intent.SetType("image/*");
            intent.PutExtra(Intent.ExtraAllowMultiple, true);
            intent.SetAction(Intent.ActionGetContent);

            //Start the picture - picker activity(resumes in MainActivity.cs)
            MainActivity.Instance.StartActivityForResult(
                Intent.CreateChooser(intent, "Select Photo"),
                MainActivity.PickImageId);

            //intent.SetAction(Intent.ActionGetContent);
            //((MainActivity)Forms.Context).StartActivityForResult(
            //    Intent.CreateChooser(intent, "Select photo"), 0);

            // Save the TaskCompletionSource object as a MainActivity property
            MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource <Stream>();

            // Return Task object
            return(MainActivity.Instance.PickImageTaskCompletionSource.Task);
        }
            public void OnClick(View v)
            {
                try
                {
                    Intent intent = new Intent(Intent.ActionSend);
                    intent.SetType("text/plain");
                    intent.PutExtra(Intent.ExtraText, result.EventName + "\n" + result.EventDescription + "\n" + result.EventDate + "\n" + "Download weclip from http://www.weclip.com");
                    activity.StartActivity(Intent.CreateChooser(intent, "Share To"));

                    //   ShareDialog shareDialog = new ShareDialog(activity);
                    //   //  shareDialog.RegisterCallback(callbackManager, this);

                    //   ShareLinkContent.Builder shareLinkContentBuilder = new ShareLinkContent.Builder().
                    //         SetContentTitle(result.EventName).
                    //   SetContentDescription(result.EventDescription);
                    //shareLinkContentBuilder.SetContentUrl(Android.Net.Uri.Parse(GlobalClass.strImagePath + result.EventPic));
                    //   ShareLinkContent shareLinkContent = shareLinkContentBuilder.Build();
                    //   shareDialog.Show(shareLinkContent);
                }
                catch (System.Exception ex)
                {
                    Log.Debug("Erorr", ex.Message);
                }
            }
示例#15
0
        private void TakePicture_Click(object sender, EventArgs e)
        {
            string[] items = { "Take Photo", "Choose from Library", "Cancel" };
            using (var dialogBuilder = new AlertDialog.Builder(this))
            {
                dialogBuilder.SetTitle("Add Photo");
                Intent intent;
                dialogBuilder.SetItems(items, (o, args) =>
                {
                    switch (args.Which)
                    {
                    case 0:
                        intent             = new Intent(MediaStore.ActionImageCapture);
                        var imageDirectory = new File(Android.OS.Environment.GetExternalStoragePublicDirectory(
                                                          Android.OS.Environment.DirectoryPictures), "SuperKittens");

                        if (!imageDirectory.Exists())
                        {
                            imageDirectory.Mkdirs();
                        }
                        _imageFile = new File(imageDirectory, $"superKitten_{Guid.NewGuid()}.jpg");
                        intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_imageFile));

                        StartActivityForResult(intent, RequestCamera);
                        break;

                    case 1:
                        intent = new Intent(Intent.ActionPick, MediaStore.Images.Media.ExternalContentUri);
                        intent.SetType("image/*");
                        StartActivityForResult(Intent.CreateChooser(intent, "Select picture"), SelectFile);
                        break;
                    }
                });
                dialogBuilder.Show();
            }
        }
示例#16
0
        static Task PlatformOpenAsync(OpenFileRequest request)
        {
            var contentUri = Platform.GetShareableFileUri(request.File.FullPath);

            var intent = new Intent(Intent.ActionView);

            intent.SetDataAndType(contentUri, request.File.ContentType);
            intent.SetFlags(ActivityFlags.GrantReadUriPermission);

            var chooserIntent = Intent.CreateChooser(intent, request.Title ?? string.Empty);
            var flags         = ActivityFlags.ClearTop | ActivityFlags.NewTask;

#if __ANDROID_24__
            if (Platform.HasApiLevelN)
            {
                flags |= ActivityFlags.LaunchAdjacent;
            }
#endif
            chooserIntent.SetFlags(flags);

            Platform.AppContext.StartActivity(chooserIntent);

            return(Task.CompletedTask);
        }
示例#17
0
        public void redirectToMap(string address)
        {
            Coordinates coordinates = new Coordinates();

            bool isFound = false;

            foreach (var item in coordinates.coordinates)
            {
                if (item.address.Trim().ToLower().Equals(address.ToLower()))
                {
                    isFound = true;
                    //string coordString="geo:"+item.latitude+","+item.longitude+"q=vaimik";
                    string coordString = "geo:" + item.latitude + "," + item.longitude + "?q=" + address;
                    var    geoUri      = Android.Net.Uri.Parse(coordString);
                    var    mapIntent   = new Intent(Intent.ActionView, geoUri);
                    Intent mapchooser  = Intent.CreateChooser(mapIntent, "Open Map");
                    StartActivity(mapchooser);
                }
            }
            if (!isFound)
            {
                Toast.MakeText(this, "Address Not found", ToastLength.Long);
            }
        }
示例#18
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.layoutinfooffline);
            //////////////////////////////////////mapeo
            var nombre = FindViewById <TextView>(Resource.Id.textView3);

            link = FindViewById <LinearLayout>(Resource.Id.boton2);
            var foto = FindViewById <ImageView>(Resource.Id.imageView2);

            fondo = FindViewById <ImageView>(Resource.Id.imageView10);
            var cerrar = FindViewById <ImageView>(Resource.Id.imageView1);

            playpause = FindViewById <ImageView>(Resource.Id.imageView3);
            barra     = FindViewById <SeekBar>(Resource.Id.seekBar1);
            var botoncarpeta = FindViewById <LinearLayout>(Resource.Id.boton1);

            //  var reproducirext = FindViewById<ImageView>(Resource.Id.imageView11);

            ///////////////////////////////////////////////////////
            this.SetFinishOnTouchOutside(true);
            nombre.Text     = Intent.GetStringExtra("nombre");
            linkvid         = Intent.GetStringExtra("link");
            nombre.Selected = true;
            link.Selected   = true;



            if (Clouding_service.gettearinstancia() != null)
            {
                estabareproduciendo = Clouding_service.gettearinstancia().musicaplayer.IsPlaying;
            }
            else
            if (Clouding_serviceoffline.gettearinstancia() != null)
            {
                estabareproduciendo = Clouding_serviceoffline.gettearinstancia().musicaplayer.IsPlaying;
            }

            /*
             *          if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr1)
             *          {
             *
             *              fondo.SetImageBitmap(CreateBlurredImage(20, link.Text));
             *          }
             *
             */


            playpause.SetBackgroundResource(Resource.Drawable.playbutton2);
            using (var imagen = BitmapFactory.DecodeFile(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + linkvid.Split('=')[1]))
            {
                foto.SetImageBitmap(getRoundedShape(imagen));
            }

            animar5(foto);
            new Thread(() =>
            {
                ponerporciento();
            }).Start();

            //////////////////////////////////////clicks
            barra.ProgressChanged += (aass, asda) =>
            {
                if (asda.FromUser)
                {
                    musicaplayer.SeekTo(asda.Progress);
                }
            };
            link.Click += delegate
            {
                var uri    = Android.Net.Uri.Parse(linkvid);
                var intent = new Intent(Intent.ActionView, uri);
                StartActivity(intent);
            };
            botoncarpeta.Click += delegate
            {
                string path = Intent.GetStringExtra("path");

                // Verify the intent will resolve to at least one activity if (intent.resolveActivity(getPackageManager()) != null) { startActivity(chooser); }



                Intent intentssdd = new Intent(Intent.ActionView);
                intentssdd.SetDataAndType(Android.Net.Uri.Parse(path), "resource/folder");
                Intent chooser = Intent.CreateChooser(intentssdd, "tumama");

                if (intentssdd.ResolveActivityInfo(PackageManager, 0) != null)
                {
                    StartActivity(chooser);
                }
                else
                {
                    Toast.MakeText(this, "No hay explorador de archivos valido en su sistema android", ToastLength.Long).Show();
                }
            };

            cerrar.Click += delegate
            {
                this.Finish();
            };
            playpause.Click += delegate
            {
                if (playerseteado)
                {
                    if (musicaplayer.IsPlaying)
                    {
                        playpause.SetBackgroundResource(Resource.Drawable.playbutton2);
                        musicaplayer.Pause();
                        if (estabareproduciendo)
                        {
                            if (Clouding_service.gettearinstancia() != null)
                            {
                                Clouding_service.gettearinstancia().musicaplayer.Start();
                            }
                            else
                            if (Clouding_serviceoffline.gettearinstancia() != null)
                            {
                                Clouding_serviceoffline.gettearinstancia().musicaplayer.Start();
                            }
                        }
                    }
                    else
                    {
                        playpause.SetBackgroundResource(Resource.Drawable.pausebutton2);
                        musicaplayer.Start();

                        if (estabareproduciendo)
                        {
                            if (Clouding_service.gettearinstancia() != null)
                            {
                                Clouding_service.gettearinstancia().musicaplayer.Pause();
                            }
                            else
                            if (Clouding_serviceoffline.gettearinstancia() != null)
                            {
                                Clouding_serviceoffline.gettearinstancia().musicaplayer.Pause();
                            }
                        }
                    }
                }
                else
                {
                    reproducir(Intent.GetStringExtra("path"));
                }
            };

            // Create your application here
        }
示例#19
0
        public override void OnViewCreated(View view, Bundle savedInstanceState)
        {
            base.OnViewCreated(view, savedInstanceState);

            //Checking media files list
            if (!mediaList.Any())
            {
                view.FindViewById <ImageButton>(Resource.Id.delete_button).Enabled = false;
                view.FindViewById <ImageButton>(Resource.Id.share_button).Enabled  = false;
            }

            // Populate the ViewPager and implement a cache of two media items
            var mediaViewPager = view.FindViewById <ViewPager>(Resource.Id.photo_view_pager);

            mediaViewPager.OffscreenPageLimit = 2;
            mediaViewPager.Adapter            = new MediaPagerAdapter(this, this.ChildFragmentManager);

            // Make sure that the cutout "safe area" avoids the screen notch if any
            if (Build.VERSION.SdkInt >= BuildVersionCodes.P)
            {
                // Use extension method to pad "inside" view containing UI using display cutout's bounds
                view.FindViewById <ConstraintLayout>(Resource.Id.cutout_safe_area).PadWithDisplayCutout();
            }

            // Handle back button press
            view.FindViewById <ImageButton>(Resource.Id.back_button).Click += (sender, e) =>
            {
                Navigation.FindNavController(RequireActivity(), Resource.Id.fragment_container).NavigateUp();
            };

            // Handle share button press
            view.FindViewById <ImageButton>(Resource.Id.share_button).Click += (sender, e) =>
            {
                Java.IO.File mediaFile = mediaList[mediaViewPager.CurrentItem];
                // Create a sharing intent
                var intent = new Intent();
                // Infer media type from file extension
                string mediaType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(MimeTypeMap.GetFileExtensionFromUrl(mediaFile.Path));
                // Get URI from our FileProvider implementation
                Android.Net.Uri uri = FileProvider.GetUriForFile(view.Context, Context.PackageName + ".provider", mediaFile);
                // Set the appropriate intent extra, type, action and flags
                intent.PutExtra(Intent.ExtraStream, uri);
                intent.SetType(mediaType);
                intent.SetAction(Intent.ActionSend);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);

                // Launch the intent letting the user choose which app to share with
                StartActivity(Intent.CreateChooser(intent, GetString(Resource.String.share_hint)));
            };

            // Handle delete button press
            view.FindViewById <ImageButton>(Resource.Id.delete_button).Click += (sender, e) =>
            {
                Java.IO.File mediaFile = mediaList[mediaViewPager.CurrentItem];
                new AlertDialog.Builder(view.Context, Android.Resource.Style.ThemeMaterialDialog)
                .SetTitle(GetString(Resource.String.delete_title))
                .SetMessage(GetString(Resource.String.delete_dialog))
                .SetIcon(Android.Resource.Drawable.IcDialogAlert)
                .SetPositiveButton(Android.Resource.String.Yes, (sender2, e2) =>
                {
                    // Delete current photo
                    mediaFile.Delete();

                    // Send relevant broadcast to notify other apps of deletion
                    MediaScannerConnection.ScanFile(view.Context, new[] { mediaFile.AbsolutePath }, null, null);

                    // Notify our view pager
                    mediaList.RemoveAt(mediaViewPager.CurrentItem);
                    mediaViewPager.Adapter.NotifyDataSetChanged();

                    // If all photos have been deleted, return to camera
                    if (!mediaList.Any())
                    {
                        Navigation.FindNavController(RequireActivity(), Resource.Id.fragment_container).NavigateUp();
                    }
                })
                .SetNegativeButton(Android.Resource.String.No, handler: null)
                .Create().ShowImmersive();
            };
        }
示例#20
0
        protected override void Setup(CompositeDisposable disposable)
        {
            SetSupportActionBar(UserDetailsToolBar);

            var json = Intent.GetStringExtra(GetString(Resource.String.UserDetailsIntentKey));

            if (!String.IsNullOrWhiteSpace(json))
            {
                ViewModel = CompositionRoot.CreateUserDetailsViewModel(JsonConvert.DeserializeObject <UserModel>(json));
            }
            else
            {
                ViewModel = CompositionRoot.CreateUserDetailsViewModel(null);
            }


            this.OneWayBind(ViewModel,
                            vm => vm.UserName,
                            v => v.UserDetailsCollapsingToolBar.Title,
                            txt => !String.IsNullOrWhiteSpace(txt) ? txt : "Welcome")
            .DisposeWith(disposable);


            this.Bind(ViewModel, vm => vm.UserName, v => v.UserName.Text)
            .DisposeWith(disposable);

            this.WhenAnyValue(v => v.ViewModel.UserNameIsUnique, v => v.ViewModel.UserNameIsValid)
            .Subscribe(items =>
            {
                if (!items.Item1)
                {
                    UserNameTextInputLayout.Error = GetString(Resource.String.UserNameIsUnique);
                    return;
                }

                if (!items.Item2)
                {
                    UserNameTextInputLayout.Error = GetString(Resource.String.UserNameIsInvalid);
                    return;
                }

                UserNameTextInputLayout.Error = String.Empty;
            })
            .DisposeWith(disposable);



            this.Bind(ViewModel, vm => vm.Password, v => v.Password.Text)
            .DisposeWith(disposable);

            this.OneWayBind(ViewModel, vm => vm.ShowPasswordIsInvalid, v => v.PasswordTextInputLayout.Error,
                            result => result ? GetString(Resource.String.PasswordIsInvalid) : String.Empty)
            .DisposeWith(disposable);



            this.WhenAnyValue(x => x.ViewModel.UserImage)
            .Subscribe(bytes =>
            {
                if (bytes == null || bytes.Length == 0)
                {
                    ToolBarImage.SetImageResource(0);
                }
                else
                {
                    Func <CancellationToken, Task <Stream> > processMe =
                        (ct) =>
                    {
                        return(Task.FromResult((System.IO.Stream) new MemoryStream(bytes ?? new byte[0])));
                    };

                    ImageService.Instance
                    .LoadStream(processMe)
                    .Into(ToolBarImage);
                }
            })
            .DisposeWith(disposable);



            this.OneWayBind(ViewModel, vm => vm.EnableSaveButton, v => v.UpdateUser.Enabled)
            .DisposeWith(disposable);

            this.BindCommand(ViewModel, vm => vm.SaveUser, v => v.UpdateUser)
            .DisposeWith(disposable);


            this.WhenAnyObservable(v => v.ViewModel.GoBackWithResult)
            .Subscribe(results =>
            {
                Intent intent = new Intent();
                intent.PutExtra(
                    Resources.GetString(Resource.String.UserDetailsIntentKey),
                    JsonConvert.SerializeObject(results)
                    );

                SetResult(Result.Ok, intent);
                OnBackPressed();
            })
            .DisposeWith(disposable);


            this.AddNewImageButton
            .Events()
            .Click.Subscribe(_ =>
            {
                var imageIntent = new Intent();
                imageIntent.SetType("image/*");
                imageIntent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(
                    Intent.CreateChooser(imageIntent, "Select photo"), 0);
            });

            SupportActionBar?.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar?.SetHomeButtonEnabled(true);
        }
示例#21
0
        public override bool ShouldOverrideUrlLoading(WebView webView, string url)
        {
            var scheme = "hybrid:";

            // If the URL is not our own custom scheme, just let the webView load the URL as usual
            if (!url.StartsWith(scheme))
            {
                return(false);
            }

            // This handler will treat everything between the protocol and "?"
            // as the method name.  The querystring has all of the parameters.
            var resources  = url.Substring(scheme.Length).Split('?');
            var method     = resources [0];
            var parameters = System.Web.HttpUtility.ParseQueryString(resources[1]);


            if (method == "")
            {
                var template = new TodoView()
                {
                    Model = new TodoItem()
                };
                var page = template.GenerateString();
                webView.LoadDataWithBaseURL("file:///android_asset/", page, "text/html", "UTF-8", null);
            }
            else if (method == "ViewTask")
            {
                var id       = parameters ["todoid"];
                var model    = App.Database.GetItem(Convert.ToInt32(id));
                var template = new TodoView()
                {
                    Model = model
                };
                var page = template.GenerateString();
                webView.LoadDataWithBaseURL("file:///android_asset/", page, "text/html", "UTF-8", null);
            }
            else if (method == "TextAll" || method == "TweetAll")
            {
                var todos  = App.Database.GetItemsNotDone();
                var totext = "";
                foreach (var t in todos)
                {
                    totext += t.Name + ",";
                }
                if (totext == "")
                {
                    totext = "there are no tasks to share";
                }

                try {
                    var intent = new Intent(Intent.ActionSend);
                    intent.PutExtra(Intent.ExtraText, totext);
                    intent.SetType("text/plain");
                    context.StartActivity(Intent.CreateChooser(intent, "Undone Todos"));
                } catch (Exception ex) {
                    System.Diagnostics.Debug.WriteLine(ex);
                }
            }
            else if (method == "TodoView")
            {
                // the editing form
                var button = parameters ["Button"];
                if (button == "Save")
                {
                    var id    = parameters ["id"];
                    var name  = parameters ["name"];
                    var notes = parameters ["notes"];
                    var done  = parameters ["done"];

                    var todo = new TodoItem {
                        ID    = Convert.ToInt32(id),
                        Name  = name,
                        Notes = notes,
                        Done  = (done == "on")
                    };

                    App.Database.SaveItem(todo);
                    context.Finish();
                }
                else if (button == "Delete")
                {
                    var id = parameters ["id"];

                    App.Database.DeleteItem(Convert.ToInt32(id));
                    context.Finish();
                }
                else if (button == "Cancel")
                {
                    context.Finish();
                }
                else if (button == "Speak")
                {
                    var name  = parameters ["name"];
                    var notes = parameters ["notes"];
                    if (speech == null)
                    {
                        speech = new Speech();
                    }
                    speech.Speak(context, name + " " + notes);
                }
            }


            return(true);
        }
示例#22
0
        protected override void OnCreate(Bundle bundle)
        {
            int TextSize = 20;

            base.OnCreate(bundle);

            SetContentView(Resource.Layout.HadithBrowser);

            //ActionBar
            ActionBar.NavigationMode = ActionBarNavigationMode.Standard;

            var txtHadith   = (TextView)FindViewById(Resource.Id.txtHadith);
            var btnZoomIn   = (Button)FindViewById(Resource.Id.btnZoomIn);
            var btnZoomOut  = (Button)FindViewById(Resource.Id.btnZoomOut);
            var btnNext     = (Button)FindViewById(Resource.Id.btnNext);
            var btnPrevious = (Button)FindViewById(Resource.Id.btnPrevious);
            var btnShare    = (Button)FindViewById(Resource.Id.btnShare);
            var web         = new WebView(this);

            var Hadith = Intent.GetStringExtra("Hadith") ?? "Data not available";

            if (!Intent.GetStringExtra("HadithNext1").ToString().Equals(null))
            {
                var HadithNext1 = Intent.GetStringExtra("HadithNext1") ?? "Data not available";
                btnNext.Click += delegate
                {
                    txtHadith.Text = HadithNext1;
                };
            }
            if (!Intent.GetStringExtra("HadithPrevious1").ToString().Equals(null))
            {
                var HadithPrevious1 = Intent.GetStringExtra("HadithPrevious1") ?? "Data not available";
                btnPrevious.Click += delegate
                {
                    txtHadith.Text = HadithPrevious1;
                };
            }

            txtHadith.Text = Hadith;

            btnZoomIn.Click += delegate
            {
                TextSize++;
                txtHadith.TextSize = TextSize;
            };

            btnZoomOut.Click += delegate
            {
                TextSize--;
                txtHadith.TextSize = TextSize;
            };

            btnShare.Click += (s, arg) =>
            {
                PopupMenu menu = new PopupMenu(this, btnShare);

                // with Android 4 Inflate can be called directly on the menu
                menu.Inflate(IslamicHadithAND.Resource.Menu.menuShare);

                menu.MenuItemClick += (s1, arg1) =>
                {
                    switch (arg1.Item.ItemId)
                    {
                    case Resource.Id.btnShareFacebook:
                        web.LoadUrl("http://www.facebook.com");
                        break;

                    case Resource.Id.btnShareTwitter:
                        web.LoadUrl("http://www.twitter.com");
                        break;

                    case Resource.Id.btnShareWhatsApp:
                        var whatsapp = new Intent(Intent.ActionSend);
                        whatsapp.PutExtra(Intent.DataString, txtHadith.Text);
                        StartActivity(Intent.CreateChooser(whatsapp, "مشاركة الحديث"));
                        break;

                    case Resource.Id.btnCopyToClipboard:
                        var clipboard = (ClipboardManager)GetSystemService(ClipboardService);
                        var clip      = ClipData.NewPlainText("Hadith", txtHadith.Text);
                        clipboard.PrimaryClip = clip;
                        Toast.MakeText(this, "تم", ToastLength.Long).Show();
                        break;

                    default:
                        break;
                    }
                };

                menu.Show();
            };
        }
示例#23
0
        public void ComposeEmail(
            IEnumerable <string> to, IEnumerable <string> cc = null, string subject = null,
            string body = null, bool isHtml = false,
            IEnumerable <EmailAttachment> attachments = null, string dialogTitle = null)
        {
            // http://stackoverflow.com/questions/2264622/android-multiple-email-attachments-using-intent
            var emailIntent = new Intent(Intent.ActionSendMultiple);

            if (to != null)
            {
                emailIntent.PutExtra(Intent.ExtraEmail, to.ToArray());
            }
            if (cc != null)
            {
                emailIntent.PutExtra(Intent.ExtraCc, cc.ToArray());
            }
            emailIntent.PutExtra(Intent.ExtraSubject, subject ?? string.Empty);

            body = body ?? string.Empty;

            if (isHtml)
            {
                emailIntent.SetType("text/html");

                ICharSequence htmlBody;
                if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
                {
                    htmlBody = Html.FromHtml(body, FromHtmlOptions.ModeLegacy);
                }
                else
#pragma warning disable CS0618 // Type or member is obsolete
                {
                    htmlBody = Html.FromHtml(body);
                }
#pragma warning restore CS0618 // Type or member is obsolete

                emailIntent.PutExtra(Intent.ExtraText, htmlBody);
            }
            else
            {
                emailIntent.SetType("text/plain");
                emailIntent.PutExtra(Intent.ExtraText, body);
            }

            if (attachments != null)
            {
                var uris = new List <IParcelable>();

                DoOnActivity(activity => {
                    filesToDelete = new List <File>();

                    foreach (var file in attachments)
                    {
                        // fix for Gmail error
                        using (var memoryStream = new MemoryStream())
                        {
                            var fileName  = Path.GetFileNameWithoutExtension(file.FileName);
                            var extension = Path.GetExtension(file.FileName);

                            // save file in external cache (required so Gmail app can independently access it, otherwise Gmail won't take the attachment)
                            var newFile = new File(activity.ExternalCacheDir, fileName + extension);

                            file.Content.CopyTo(memoryStream);
                            var bytes = memoryStream.ToArray();
                            using (var localFileStream = new FileOutputStream(newFile))
                            {
                                localFileStream.Write(bytes);
                            }

                            newFile.SetReadable(true, false);
                            newFile.DeleteOnExit();
                            uris.Add(Uri.FromFile(newFile));

                            filesToDelete.Add(newFile);
                        }
                    }
                });

                if (uris.Any())
                {
                    emailIntent.PutParcelableArrayListExtra(Intent.ExtraStream, uris);
                }
            }

            emailIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
            emailIntent.AddFlags(ActivityFlags.GrantWriteUriPermission);

            // fix for GMail App 5.x (File not found / permission denied when using "StartActivity")
            StartActivityForResult(0, Intent.CreateChooser(emailIntent, dialogTitle ?? string.Empty));
        }
示例#24
0
        public override Task <TaskCommandResult> ExecuteAsync(SaveFileStreamContext request)
        {
            var retResult = new TaskCommandResult();

            string root = null;

            if (Android.OS.Environment.IsExternalStorageEmulated)

            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
            {
                root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }

            File myDir = new File(root + "/Syncfusion");

            myDir.Mkdir();

            File file = new File(myDir, request.FileName);

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

            try

            {
                FileOutputStream outs = new FileOutputStream(file);

                outs.Write(request.Stream.ToArray());

                outs.Flush();

                outs.Close();
            }
            catch (Exception e)
            {
                retResult.Notification.Add(e.Message);
            }

            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.FromResult(new TaskCommandResult()));

            //for platform implementations, see https://help.syncfusion.com/file-formats/pdf/working-with-xamarin
        }
示例#25
0
        public void Setup()
        {
            var nativeBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (!nativeBluetoothAdapter.IsEnabled)
            {
                System.Console.WriteLine("Enabling bluetooth");
                Intent enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
                StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                return;
            }

            var androidBluetoothAdapter = new AndroidBluetoothAdapterFactory().Create(this, ApplicationContext, nativeBluetoothAdapter);
            var client = CampfireNetClientBuilder.CreateNew()
                         .WithDevelopmentNetworkClaims()
                         .WithBluetoothAdapter(androidBluetoothAdapter)
                         .Build();
            var identity = client.Identity;

            var sync = new object();

            client.MessageReceived += e => {
                lock (sync) {
                    var s = Encoding.UTF8.GetString(e.Message.DecryptedPayload, 0, e.Message.DecryptedPayload.Length);
                    uiDispatchHandler.ObtainMessage(LOG_MESSAGE, "RECV: " + s).SendToTarget();
                }
            };


            generateButton.Click += (s, e) => {
                var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                path = Path.Combine(path, $"trust_chain_{IdentityManager.GetIdentityString(identity.PublicIdentityHash)}.bin");

                if (!File.Exists(path) && identity.TrustChain == null)
                {
                    identity.GenerateRootChain();

                    using (var stream = new FileStream(path, FileMode.Create))
                        using (var writer = new BinaryWriter(stream)) {
                            writer.Write(TrustChainUtil.SerializeTrustChain(identity.TrustChain));
                        }
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Trust chain already exists.", ToastLength.Short).Show();
                }
            };

            sendButton.Click += (s, e) => {
                var filename = $"trust_chain_{IdentityManager.GetIdentityString(identity.PublicIdentityHash)}.bin";
                var path     = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                path = Path.Combine(path, filename);

                // TODO fix
                if (!File.Exists(path))
                {
                    Toast.MakeText(ApplicationContext, "Cannot find file in Download folder.", ToastLength.Short).Show();
                    return;
                }

                var tmpFolder = Environment.ExternalStorageDirectory.ToString();
                var tmpFile   = Path.Combine(tmpFolder, filename);
                File.Copy(path, tmpFile, true);

                var file = new Java.IO.File(tmpFile);
                var uri  = Android.Net.Uri.FromFile(file);

                Intent email = new Intent(Intent.ActionSend);
                email.SetType("message/rfc822");
                email.PutExtra(Intent.ExtraSubject, "Trust chain addition");
                email.PutExtra(Intent.ExtraStream, uri);
                email.AddFlags(ActivityFlags.GrantReadUriPermission);

                try {
                    StartActivityForResult(Intent.CreateChooser(email, "Send mail with: "), 0);
                } catch (ActivityNotFoundException) {
                    Toast.MakeText(ApplicationContext, "There are no email clients installed.", ToastLength.Short).Show();
                }
            };

            loadButton.Click += (s, e) => {
                var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                path = Path.Combine(path, $"trust_chain_{IdentityManager.GetIdentityString(identity.PublicIdentityHash)}.bin");

                if (!File.Exists(path))
                {
                    Toast.MakeText(ApplicationContext, "Cannot find own trust chain file in Download folder.", ToastLength.Short).Show();
                    return;
                }

                byte[] data = File.ReadAllBytes(path);

                try {
                    identity.AddTrustChain(data);
                    Toast.MakeText(ApplicationContext, "Successfully loaded trust chain.", ToastLength.Short).Show();
                } catch (BadTrustChainException) {
                    Toast.MakeText(ApplicationContext, "Invalid trust chain found.", ToastLength.Short).Show();
                }
            };

            clearButton.Click += (s, e) => {
                var privateFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                var files         = Directory.GetFiles(privateFolder);

                foreach (var file in files)
                {
                    File.Delete(file);
                }

                //var path = Path.Combine(privateFolder, PRIVATE_KEY_FILE);
                //identity.SaveKey(path);
            };


            sendTextButton.Click += (s, e) => {
                var text = inputText.Text;
                client.BroadcastAsync(Encoding.UTF8.GetBytes(text)).Forget();
                inputText.Text = "";
            };

            client.RunAsync().Forget();
        }
示例#26
0
        private void ShowSftpDialog(Activity activity, Util.FileSelectedHandler onStartBrowse, Action onCancel, string defaultPath)
        {
#if !EXCLUDE_JAVAFILESTORAGE && !NoNet
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            View dlgContents            = activity.LayoutInflater.Inflate(Resource.Layout.sftpcredentials, null);

            var spinner = dlgContents.FindViewById <Spinner>(Resource.Id.sftp_auth_mode_spinner);
            dlgContents.FindViewById <Button>(Resource.Id.send_public_key_button).Click += (sender, args) =>
            {
                var    fileStorage  = new Keepass2android.Javafilestorage.SftpStorage(activity.ApplicationContext);
                string pub_filename = fileStorage.CreateKeyPair();

                Intent sendIntent = new Intent();
                sendIntent.SetAction(Intent.ActionSend);
                sendIntent.PutExtra(Intent.ExtraText, System.IO.File.ReadAllText(pub_filename));

                sendIntent.PutExtra(Intent.ExtraSubject, "Keepass2Android sftp public key");
                sendIntent.SetType("text/plain");
                activity.StartActivity(Intent.CreateChooser(sendIntent, "Send public key to..."));
            };


            spinner.ItemSelected += (sender, args) =>
            {
                if (spinner.SelectedItemPosition == 0)
                {
                    dlgContents.FindViewById <EditText>(Resource.Id.sftp_password).Visibility        = ViewStates.Visible;
                    dlgContents.FindViewById <Button>(Resource.Id.send_public_key_button).Visibility = ViewStates.Gone;
                }
                else
                {
                    dlgContents.FindViewById <EditText>(Resource.Id.sftp_password).Visibility        = ViewStates.Gone;
                    dlgContents.FindViewById <Button>(Resource.Id.send_public_key_button).Visibility = ViewStates.Visible;
                }
            };

            if (!defaultPath.EndsWith(_schemeSeparator))
            {
                var fileStorage = new Keepass2android.Javafilestorage.SftpStorage(activity.ApplicationContext);
                SftpStorage.ConnectionInfo ci = fileStorage.SplitStringToConnectionInfo(defaultPath);
                dlgContents.FindViewById <EditText>(Resource.Id.sftp_host).Text        = ci.Host;
                dlgContents.FindViewById <EditText>(Resource.Id.sftp_port).Text        = ci.Port.ToString();
                dlgContents.FindViewById <EditText>(Resource.Id.sftp_user).Text        = ci.Username;
                dlgContents.FindViewById <EditText>(Resource.Id.sftp_password).Text    = ci.Password;
                dlgContents.FindViewById <EditText>(Resource.Id.sftp_initial_dir).Text = ci.LocalPath;
                if (string.IsNullOrEmpty(ci.Password))
                {
                    spinner.SetSelection(1);
                }
            }

            builder.SetView(dlgContents);
            builder.SetPositiveButton(Android.Resource.String.Ok,
                                      (sender, args) =>
            {
                string host     = dlgContents.FindViewById <EditText>(Resource.Id.sftp_host).Text;
                string portText = dlgContents.FindViewById <EditText>(Resource.Id.sftp_port).Text;
                int port        = Keepass2android.Javafilestorage.SftpStorage.DefaultSftpPort;
                if (!string.IsNullOrEmpty(portText))
                {
                    int.TryParse(portText, out port);
                }
                string user        = dlgContents.FindViewById <EditText>(Resource.Id.sftp_user).Text;
                string password    = dlgContents.FindViewById <EditText>(Resource.Id.sftp_password).Text;
                string initialPath = dlgContents.FindViewById <EditText>(Resource.Id.sftp_initial_dir).Text;
                if (string.IsNullOrEmpty(initialPath))
                {
                    initialPath = "/";
                }
                string sftpPath = new Keepass2android.Javafilestorage.SftpStorage(activity.ApplicationContext).BuildFullPath(host, port, initialPath, user,
                                                                                                                             password);
                onStartBrowse(sftpPath);
            });
            EventHandler <DialogClickEventArgs> evtH = new EventHandler <DialogClickEventArgs>((sender, e) => onCancel());

            builder.SetNegativeButton(Android.Resource.String.Cancel, evtH);
            builder.SetTitle(activity.GetString(Resource.String.enter_sftp_login_title));
            Dialog dialog = builder.Create();

            dialog.Show();
#endif
        }
        public async Task SaveAndView(string fileName, String contentType, MemoryStream stream, PDFOpenContext context)
        {
            string exception = string.Empty;
            string root      = null;

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

            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
            {
                root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }

            Java.IO.File myDir = new Java.IO.File(root + "/PDFFiles");
            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 = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
                string mimeType  = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                Intent intent    = new Intent(Intent.ActionView);
                intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
                Android.Net.Uri path = FileProvider.GetUriForFile(Forms.Context, Android.App.Application.Context.PackageName + ".provider", file);
                intent.SetDataAndType(path, mimeType);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);

                switch (context)
                {
                case PDFOpenContext.InApp:
                    Forms.Context.StartActivity(intent);
                    break;

                case PDFOpenContext.ChooseApp:
                    Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
                    break;

                default:
                    break;
                }
            }
        }
示例#28
0
 private void OnAddImageButtonClick(object sender, EventArgs eventArgs)
 {
     Intent.SetType(IMAGE_TYPE);
     Intent.SetAction(Intent.ActionGetContent);
     StartActivityForResult(Intent.CreateChooser(Intent, CREATE_CHOOSER_TITLE), PickImageId);
 }
示例#29
0
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            Log.Info(Tag, "Menu Item selected " + item);

            if (item == _itemPickPhoto)
            {
                var imageIntent = new Intent();
                imageIntent.SetType("image/*");
                imageIntent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(Intent.CreateChooser(imageIntent, "Select photo"), 0);
            }
            else if (item == _itemGray)
            {
                // 灰度图
                _gray = new Mat(_raw.Width(), _raw.Height(), CvType.Cv8uc1);
                Imgproc.CvtColor(_raw, _gray, Imgproc.ColorRgb2gray);
                ShowImage(_gray);
            }
            else if (item == _itemThreshold)
            {
                // 二值化
                _threshold = new Mat(_image.Width, _image.Height, CvType.Cv8uc1);
                Imgproc.Threshold(_gray, _threshold, 168, 255, Imgproc.ThreshBinary);
                ShowImage(_threshold);
            }
            else if (item == _itemFindContours)
            {
                // 查找最大连通区域
                IList <MatOfPoint> contours = new JavaList <MatOfPoint>();
                Mat hierarchy = new Mat();
                var target    = _threshold.Clone();
                Imgproc.FindContours(target, contours, hierarchy, Imgproc.RetrExternal, Imgproc.ChainApproxNone);

                MatOfPoint max = new MatOfPoint();
                double     contour_area_max = 0;
                if (contours.Any())
                {
                    foreach (var contour in contours)
                    {
                        var contour_area_temp = Math.Abs(Imgproc.ContourArea(contour));
                        if (contour_area_temp > contour_area_max)
                        {
                            contour_area_max = contour_area_temp;
                            max = contour;
                        }
                    }
                }

                var last = new JavaList <MatOfPoint>();
                last.Add(max);

                Imgproc.DrawContours(_raw, last, -1, new Scalar(255, 0, 0));

                ShowImage(_raw);
            }
            else if (item == _itemCreateTrimap)
            {
                // 生成三元图  暂时先用生成的图替代
                var imageIntent = new Intent();
                imageIntent.SetType("image/*");
                imageIntent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(Intent.CreateChooser(imageIntent, "Select photo"), 1);
            }
            else if (item == _itemSharedMatting)
            {
                // 扣图
                var sharedMatting = new SharedMatting();
                sharedMatting.SetImage(_raw);
                sharedMatting.SetTrimap(_trimap);
                sharedMatting.SolveAlpha();
            }

            return(base.OnOptionsItemSelected(item));
        }
示例#30
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);

            //force max brightness on screen.
            Window.Attributes.ScreenBrightness = 1f;

            //Full screen and hide nav bar.
            View decorView    = Window.DecorView;
            var  uiOptions    = (int)decorView.SystemUiVisibility;
            var  newUiOptions = (int)uiOptions;

            newUiOptions |= (int)SystemUiFlags.LowProfile;
            newUiOptions |= (int)SystemUiFlags.Fullscreen;
            newUiOptions |= (int)SystemUiFlags.HideNavigation;
            newUiOptions |= (int)SystemUiFlags.Immersive;
            // This option will make bars disappear by themselves
            newUiOptions |= (int)SystemUiFlags.ImmersiveSticky;
            decorView.SystemUiVisibility = (StatusBarVisibility)newUiOptions;

            //Keep screen from dimming.
            this.Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn);


            onScreenJoyL = FindViewById <JoystickView>(Resource.Id.joystickViewL);
            onScreenJoyR = FindViewById <JoystickView>(Resource.Id.joystickViewR);

            takeoffButton      = FindViewById <ImageButton>(Resource.Id.takeoffButton);
            throwTakeoffButton = FindViewById <ImageButton>(Resource.Id.throwTakeoffButton);

            //subscribe to Tello connection events
            Tello.onConnection += (Tello.ConnectionState newState) =>
            {
                //Update state on screen
                Button cbutton = FindViewById <Button>(Resource.Id.connectButton);

                //If not connected check to see if connected to tello network.
                if (newState != Tello.ConnectionState.Connected)
                {
                    WifiManager wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
                    string      ip          = Formatter.FormatIpAddress(wifiManager.ConnectionInfo.IpAddress);
                    if (!ip.StartsWith("192.168.10."))
                    {
                        //CrossTextToSpeech.Current.Speak("No network found.");
                        //Not connected to network.
                        RunOnUiThread(() => {
                            cbutton.Text = "Not Connected. Touch Here.";
                            cbutton.SetBackgroundColor(Android.Graphics.Color.ParseColor("#55ff3333"));
                        });
                        return;
                    }
                }
                if (newState == Tello.ConnectionState.Connected)
                {
                    //Tello.queryMaxHeight();
                    //Override max hei on connect.
                    Tello.setMaxHeight(30);//meters
                    Tello.queryMaxHeight();

                    //Tello.queryAttAngle();
                    Tello.setAttAngle(25);
                    //Tello.queryAttAngle();

                    Tello.setJpgQuality(Preferences.jpgQuality);

                    CrossTextToSpeech.Current.Speak("Connected");

                    Tello.setPicVidMode(picMode);//0=picture(960x720)

                    Tello.setEV(Preferences.exposure);
                }
                if (newState == Tello.ConnectionState.Disconnected)
                {
                    //if was connected then warn.
                    if (Tello.connectionState == Tello.ConnectionState.Connected)
                    {
                        CrossTextToSpeech.Current.Speak("Disconnected");
                    }
                }
                //update connection state button.
                RunOnUiThread(() => {
                    cbutton.Text = newState.ToString();
                    if (newState == Tello.ConnectionState.Connected)
                    {
                        cbutton.SetBackgroundColor(Android.Graphics.Color.ParseColor("#6090ee90"));//transparent light green.
                    }
                    else
                    {
                        cbutton.SetBackgroundColor(Android.Graphics.Color.ParseColor("#ffff00"));//yellow
                    }
                });
            };
            var modeTextView   = FindViewById <TextView>(Resource.Id.modeTextView);
            var hSpeedTextView = FindViewById <TextView>(Resource.Id.hSpeedTextView);
            var vSpeedTextView = FindViewById <TextView>(Resource.Id.vSpeedTextView);
            var heiTextView    = FindViewById <TextView>(Resource.Id.heiTextView);
            var batTextView    = FindViewById <TextView>(Resource.Id.batTextView);
            var wifiTextView   = FindViewById <TextView>(Resource.Id.wifiTextView);

            //Log file setup.
            var logPath      = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, "aTello/logs/");;
            var logStartTime = DateTime.Now;
            var logFilePath  = logPath + logStartTime.ToString("yyyy-dd-M--HH-mm-ss") + ".csv";

            if (doStateLogging)
            {
                //write header for cols in log.
                System.IO.Directory.CreateDirectory(logPath);
                File.WriteAllText(logFilePath, "time," + Tello.state.getLogHeader());
            }

            //subscribe to Tello update events
            Tello.onUpdate += (Tello.FlyData newState) =>
            {
                if (doStateLogging)
                {
                    //write update to log.
                    var elapsed = DateTime.Now - logStartTime;
                    File.AppendAllText(logFilePath, elapsed.ToString(@"mm\:ss\:ff\,") + newState.getLogLine());
                }

                RunOnUiThread(() => {
                    //Update state on screen

                    modeTextView.Text   = "FM:" + newState.flyMode;
                    hSpeedTextView.Text = string.Format("HS:{0: 0.0;-0.0}m/s", (float)newState.flySpeed / 10);
                    vSpeedTextView.Text = string.Format("VS:{0: 0.0;-0.0}m/s", (float)newState.verticalSpeed / 10);
                    heiTextView.Text    = string.Format("Hei:{0: 0.0;-0.0}m", (float)newState.height / 10);

                    if (Tello.controllerState.speed > 0)
                    {
                        hSpeedTextView.SetBackgroundColor(Android.Graphics.Color.IndianRed);
                    }
                    else
                    {
                        hSpeedTextView.SetBackgroundColor(Android.Graphics.Color.Transparent);
                    }

                    batTextView.Text  = "Bat:" + newState.batteryPercentage;
                    wifiTextView.Text = "Wifi:" + newState.wifiStrength;

                    //acstat.Text = str;
                    if (Tello.state.flying)
                    {
                        takeoffButton.SetImageResource(Resource.Drawable.land);
                    }
                    else if (!Tello.state.flying)
                    {
                        takeoffButton.SetImageResource(Resource.Drawable.takeoff_white);
                    }
                });
            };

            var videoFrame  = new byte[100 * 1024];
            var videoOffset = 0;

            Video.Decoder.surface = FindViewById <SurfaceView>(Resource.Id.surfaceView).Holder.Surface;

            var path = "aTello/video/";

            System.IO.Directory.CreateDirectory(Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, path + "cache/"));
            videoFilePath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, path + "cache/" + DateTime.Now.ToString("MMMM dd yyyy HH-mm-ss") + ".h264");

            FileStream videoStream = null;

            startUIUpdateThread();
            //updateUI();//hide record light etc.

            //subscribe to Tello video data
            Tello.onVideoData += (byte[] data) =>
            {
                totalVideoBytesReceived += data.Length;
                //Handle recording.
                if (true)                                                             //videoFilePath != null)
                {
                    if (data[2] == 0 && data[3] == 0 && data[4] == 0 && data[5] == 1) //if nal
                    {
                        var nalType = data[6] & 0x1f;
                        //                       if (nalType == 7 || nalType == 8)
                        {
                            if (toggleRecording)
                            {
                                if (videoStream != null)
                                {
                                    videoStream.Close();
                                }
                                videoStream = null;

                                isRecording     = !isRecording;
                                toggleRecording = false;
                                if (isRecording)
                                {
                                    videoFilePath      = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, path + DateTime.Now.ToString("MMMM dd yyyy HH-mm-ss") + ".h264");
                                    startRecordingTime = DateTime.Now;
                                    CrossTextToSpeech.Current.Speak("Recording");
                                    updateUI();
                                }
                                else
                                {
                                    videoFilePath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, path + "cache/" + DateTime.Now.ToString("MMMM dd yyyy HH-mm-ss") + ".h264");
                                    CrossTextToSpeech.Current.Speak("Recording stopped");
                                    updateUI();
                                }
                            }
                        }
                    }

                    if ((isRecording || Preferences.cacheVideo))
                    {
                        if (videoStream == null)
                        {
                            videoStream = new FileStream(videoFilePath, FileMode.Append);
                        }

                        if (videoStream != null)
                        {
                            //Save raw data minus sequence.
                            videoStream.Write(data, 2, data.Length - 2);//Note remove 2 byte seq when saving.
                        }
                    }
                }

                //Handle video display.
                if (true)//video decoder tests.
                {
                    //Console.WriteLine("1");

                    if (data[2] == 0 && data[3] == 0 && data[4] == 0 && data[5] == 1)//if nal
                    {
                        var nalType = data[6] & 0x1f;
                        if (nalType == 7 || nalType == 8)
                        {
                        }
                        if (videoOffset > 0)
                        {
                            aTello.Video.Decoder.decode(videoFrame.Take(videoOffset).ToArray());
                            videoOffset = 0;
                        }
                        //var nal = (received.bytes[6] & 0x1f);
                        //if (nal != 0x01 && nal != 0x07 && nal != 0x08 && nal != 0x05)
                        //    Console.WriteLine("NAL type:" + nal);
                    }
                    //todo. resquence frames.
                    Array.Copy(data, 2, videoFrame, videoOffset, data.Length - 2);
                    videoOffset += (data.Length - 2);
                }
            };

            onScreenJoyL.onUpdate += OnTouchJoystickMoved;
            onScreenJoyR.onUpdate += OnTouchJoystickMoved;



            Tello.startConnecting();//Start trying to connect.

            //Clicking on network state button will show wifi connection page.
            Button button = FindViewById <Button>(Resource.Id.connectButton);

            button.Click += delegate {
                WifiManager wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
                string      ip          = Formatter.FormatIpAddress(wifiManager.ConnectionInfo.IpAddress);
                if (!ip.StartsWith("192.168.10."))//Already connected to network?
                {
                    StartActivity(new Intent(Android.Net.Wifi.WifiManager.ActionPickWifiNetwork));
                }
            };


            takeoffButton.Click += delegate {
                if (Tello.connected && !Tello.state.flying)
                {
                    Tello.takeOff();
                }
                else if (Tello.connected && Tello.state.flying)
                {
                    Tello.land();
                }
            };
            throwTakeoffButton.Click += delegate {
                if (Tello.connected && !Tello.state.flying)
                {
                    Tello.throwTakeOff();
                }
                else if (Tello.connected && Tello.state.flying)
                {
                    //Tello.land();
                }
            };
            var pictureButton = FindViewById <ImageButton>(Resource.Id.pictureButton);

            Tello.picPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, "aTello/pics/");
            System.IO.Directory.CreateDirectory(Tello.picPath);


            cameraShutterSound.Load("cameraShutterClick.mp3");
            pictureButton.Click += delegate
            {
                Tello.takePicture();
                cameraShutterSound.Play();
            };
            pictureButton.LongClick += delegate
            {
                //Toggle
                picMode = picMode == 1?0:1;
                Tello.setPicVidMode(picMode);
                aTello.Video.Decoder.reconfig();
            };

            var recordButton = FindViewById <ImageButton>(Resource.Id.recordButton);

            recordButton.Click += delegate
            {
                toggleRecording = true;
            };

            var galleryButton = FindViewById <ImageButton>(Resource.Id.galleryButton);

            galleryButton.Click += async delegate
            {
                //var uri = Android.Net.Uri.FromFile(new Java.IO.File(Tello.picPath));
                //shareImage(uri);
                //return;
                Intent intent = new Intent();
                intent.PutExtra(Intent.ActionView, Tello.picPath);
                intent.SetType("image/*");
                intent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(Intent.CreateChooser(intent, "Select Picture"), 1);
            };
            //Settings button
            ImageButton settingsButton = FindViewById <ImageButton>(Resource.Id.settingsButton);

            settingsButton.Click += delegate
            {
                StartActivity(typeof(SettingsActivity));
            };


            //Init joysticks.
            input_manager = (InputManager)GetSystemService(Context.InputService);
            CheckGameControllers();
        }