My problem in short, I want to take a screenshot for the screen that the user see, not my Activity. Let's say my Application is minimized, the screenshot has be taken for the screen itself, not for my app.
I red somewhere that it's possible on non rooted devices since API 19 maybe or 4.0 android, But I couldn't find a way to do that.
I tried many solutions on the internet but nothing work. Red a lot but found nothing.
I found this code but, sure it takes a screenshot for my application ( layout )
Here is the OnCreate Method :
ImageView img;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
Button btn = FindViewById<Button>(Resource.Id.button1);
img = FindViewById<ImageView>(Resource.Id.imageView1);
btn.Click += Btn_Click;
}
public byte[] CaptureScreen()
{
var view = Window.DecorView.RootView;
view.DrawingCacheEnabled = true;
Bitmap bitmap = view.GetDrawingCache(true);
byte[] bitmapData;
using (var stream = new MemoryStream())
{
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
return bitmapData;
}
To add it to an imageView when button click:
private void Btn_Click(object sender, EventArgs e)
{
Bitmap bitmap = BitmapFactory.DecodeByteArray(CaptureScreen(), 0, CaptureScreen().Length);
img.SetImageBitmap(bitmap);
}
but As I said : it takes a screenshot for the layout, not the real screen.
I tried to hide or minimize the app, but nothing happened.
I got it. After searching a lot here and there, I discover that there is a new class from java will do the job for you. It's Media projection. It'll work on Android Lollipop 5.0 or higher and doesn't need root
and all apps in play store using it as I tried to download many apps to get the idea behind taking a screenshot.
Here is the documentation about it :
https://developer.android.com/reference/android/media/projection/MediaProjection
Related
In Windows 10, when I hit e.g. SHIFT + WIN + S I can take a screenshot of my screen.
In other cases I have my webcam that can take a picture, and so on.
All those scenarios have the feature to "Share" the captured image to another app, e.g. Mail, OneNote, etc.
I would like to register my own UWP app to be the recipient of such Share, so that the user can manipulate the captured image in my UWP app.
Is there a way to configure my UWP app to do this?
Is there a way to configure my UWP app to do this?
Yes, you could make your UWP app a receiver when you want to share some content from other apps.
Declare your app as a share target. Open the manifest file. Find the Declarations tab, then choose Share Target from the Available Declarations list, and then select Add.
Set the file types and formats based on your requirements in the Declarations. For example, if you need to receive a screenshot, you will need to add Bitmap in the Data format.
Handle share activation in the App.Xaml.cs by handling the Application.OnShareTargetActivated event.
I've made a simple test about this and you could refer to it. For more information about this, you could also check this document: Receive data
Manifest file:
App.xaml.cs:
protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
ShareOperation shareOperation = args.ShareOperation;
if (shareOperation.Data.Contains(StandardDataFormats.Bitmap))
{
var imageStream = await shareOperation.Data.GetBitmapAsync();
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
Window.Current.Content = rootFrame;
}
rootFrame.Navigate(typeof(ShareImagePage), imageStream);
Window.Current.Activate();
}
}
ShareImagePage:
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Content != null)
{
IRandomAccessStreamReference imageReceived = null;
imageReceived = e.Parameter as IRandomAccessStreamReference;
using (var imageStream = await imageReceived.OpenReadAsync())
{
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(imageStream);
imgImage.Source = bitmapImage;
}
}
}
I am trying to make a page (lets call it page #2) within my Xamarin.Android app that has a button, when you press on that button the camera app opens. Then you take a picture, accept the picture you took, and then you should be brought back to the page that originally had the camera button on it (page #2), and the image you took will be displayed there under the button.
The problem is that my overridden OnActivityResult() method never gets called after you accept the picture. You press the button, the camera app opens, you take a picture, accept the picture, the camera app closes and you are brought back to the page BEFORE the camera button page (so you're on page #1 now). I think the camera app itself is crashing? I am not sure how to find those logs. Sometimes a popup will show that says "Unfortunately, the camera has stopped." I am guessing that it is the way I am trying to save the photo taken to the phone itself? The only errors I have seen are within the device log, and occasionally it will throw a permission error saying I dont have access to write to the storage device on the phone, but I have the "write" permissions in the manifest file. I am targeting API 26.
Any ideas?
Here is the method for clicking the button:
private int PIC_REQUEST_CODE = 1;
private ImageView imageView;
private Java.IO.File image;
private void Button_Click(object sender, EventArgs e)
{
Intent takePictureIntent = new Intent(MediaStore.ActionImageCapture);
if (takePictureIntent.ResolveActivity(PackageManager) != null)
{
try
{
// Create an image file name
string timeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
string imageFileName = "JPEG_" + timeStamp + "_";
Java.IO.File storageDir = GetExternalFilesDir(global::Android.OS.Environment.DirectoryPictures);
Java.IO.File image = Java.IO.File.CreateTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
global::Android.Net.Uri photoURI = FileProvider.GetUriForFile(ApplicationContext, PackageName + ".fileprovider", image);
takePictureIntent.PutExtra(MediaStore.ExtraOutput, photoURI);
takePictureIntent.AddFlags(ActivityFlags.GrantWriteUriPermission);
StartActivityForResult(takePictureIntent, PIC_REQUEST_CODE);
}
catch (Exception ex)
{
//Not sure what to do, but here's a break point at least.
Toast.MakeText(this, "blah blah something went wrong", ToastLength.Short).Show();
}
}
}
And here is my simple OnActivityResult that gets skipped/ never called:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (requestCode == PIC_REQUEST_CODE && resultCode == Result.Ok)
{
Bitmap bitmap = (Bitmap)data.Extras.Get("data");
imageView.SetImageBitmap(bitmap);
}
}
I figured out the current issue of the OnActivityResult() not being called. At the top above the class I was declaring
[Activity(Label = "#string/page_name", ScreenOrientation = ScreenOrientation.Portrait, NoHistory = true)]
The important note here is the "NoHistory=True" apparently that makes the page exit and return back to the previous page. Deleting the "NoHistory=true" worked and made it so the OnActivityResult() gets called. Some documentation about it says "A value of 'true' means that the activity will not leave a historical trace. It will not remain in the activity stack for the task, so the user will not be able to return to it" so I guess that makes sense.
I'm making a simple Windows Phone 8.1 Silverlight app. The idea is that I can make an entry with a picture (taken with the camera) and add a title and description text to it. Once an entry is saved, a button appears on the main page to view it. So I made 3 entries and they are listed on the main page, but after navigating to their pages a few times, I get a NavigationFailed along with OutOfMemoryException. The pages are simple, they only contain 1 image along with some textblocks.
I thought the issue is that the images are still in memory, that's why I try to set them to null and force the garbage collector, but that didn't help at all. What could cause the OutOfMemory-exception?
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string id= "";
if (NavigationContext.QueryString.TryGetValue("id", out id))
{
foreach (cEntry entry in helper.entries)
{
if (entry.id.ToString() == id)
{
textBlock_viewText.Text = entry.text;
textBlock_viewTitle.Text = entry.title;
using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (userStore.FileExists(entry.imageFileName))
{
using (IsolatedStorageFileStream imgStream = userStore.OpenFile(entry.imageFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(imgStream);
image_viewEntryImage.Source = bmp;
bmp = null;
}
}
}
}
}
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
image_viewEntryImage.Source = null;
GC.Collect();
}
You may need to freeze the BitmapImage.
As described here there is an issue with WPF (the typical framework for Windows Phone development) where BitmapImages can be incorrectly kept alive. While it was supposedly fixed a while back, people have reported still seeing the problem in some cases.
Instead of setting bmp as null try this.
public static void DisposeImage(BitmapImage image)
{
Uri uri= new Uri("oneXone.png", UriKind.Relative);
StreamResourceInfo sr=Application.GetResourceStream(uri);
try
{
using (Stream stream=sr.Stream)
{
image.DecodePixelWidth=1; //This is essential!
image.SetSource(stream);
}
}
catch { }
}
call this method and set source as this custom method after that assing bmp as null.
The GC not able to clear the memory. details are here Why do I get an OutOfMemoryException when I have images in my ListBox?
I have created a MediaElement in my Windows Phone 8.1 app, and I am trying to play an mp4 video. When I press the button to play the video, it shows the video's first frame (splash screen), but it never goes beyond that, and it looks like a still picture. What could I be doing wrong? I don't get any error from my MediaFailed method, either.
private void openButton_Click(object sender, RoutedEventArgs e)
{
shakeImage.Visibility = Visibility.Collapsed;
timer.Stop();
timerReset.Stop();
rotateImage.Stop();
mediaElement.Stop();
Uri explosion = new Uri(BaseUri, "Explode.mp4");
mediaElement.Source = explosion;
mediaElement.Play();
mediaElement.MediaFailed += mediaElement_MediaFailed;
}
void mediaElement_MediaFailed)object sender, ExceptionRoutedEventArgs e)
{
throw new FileNotFoundException();
}
if you are playing audio file from your phone you should change "UriKind " to "Relative" like this
Uri explosion = new Uri( "Explode.mp4",UriKind.RelativeOrAbsolute);
// or you could use this way
Stream stream = isoStore1.OpenFile("Explode.mp4", System.IO.FileMode.Open, System.IO.FileAccess.Read );
this.mediaElement.Stop();
this.mediaElement.SetSource(stream);
mediaElement.Play();
stream.Close();
Turns out it was due to Windows Phone 8 being picky about file formats and not throwing errors even though they were incorrect. I converted it to a certain wmv type and it seems to work now.
How to upload or add an Image to UIImageView directly from iPhone/Ipad Captured camera Image.
I have uploaded an image to UIImageView from photo library.
Now, I want upload an image directly after taken an image through camera to ImageView.
Please suggest me how to implement this.
using IOS 8.0
This can be accomplished very easily with the Xamarin.Mobile component, which is free and works with all platforms.
http://components.xamarin.com/view/xamarin.mobile
From the example they give:
using Xamarin.Media;
// ...
var picker = new MediaPicker ();
if (!picker.IsCameraAvailable)
Console.WriteLine ("No camera!");
else {
try {
MediaFile file = await picker.TakePhotoAsync (new StoreCameraMediaOptions {
Name = "test.jpg",
Directory = "MediaPickerSample"
});
Console.WriteLine (file.Path);
} catch (OperationCanceledException) {
Console.WriteLine ("Canceled");
}
}
After you take the picture, it is saved to the directory you specified, with the name you specified. To easily retrieve this picture and display it with your ImageView using the above example you can do the following:
//file is declared above as type MediaFile
UIImage image = new UIImage(file.Path);
//Fill in with whatever your ImageView is
yourImageView.Image = image;
Edit:
Just a note that the above needs to be asynchronous. So if you want to launch the camera from a button call, for instance, you just slightly modify the .TouchUpInside event:
exampleButton.TouchUpInside += async (object sender, EventArgs e) => {
//Code from above goes in here, make sure you have async after the +=
};
Otherwise you could wrap the code from above in a function and add async to that:
public async void CaptureImage()
{
//Code from above goes here
}
You will need to use AVFoundation to do this. Check out the AVCam sample project in Xcode:
https://developer.apple.com/library/ios/samplecode/AVCam/Introduction/Intro.html