Windows phone 8 Study Notes (7) Devices

Source: Internet
Author: User
Document directory
  • 1. PhotoCamera
  • 2. PhotoCaptureDevice

This section describes various devices supported by Windows phone 8, including cameras, device statuses, and vibration devices. There are also various sensors, including magnetic meters, accelerometer and gyroscope. You can obtain the memory, hardware, power supply, keyboard, and other statuses through the device status. You can capture photos and videos through the camera, and various sensors help you get the motion status of the device.

Quick Navigation:
I. device status
Ii. Cameras
3. Compass Sensor
Iv. Accelerometer
V. Gyroscope
6. How to vibrate mobile phones

I. device status

Through the DeviceStatus class, we can determine the status information of the device, such as the memory size, firmware version, whether the physical keyboard is deployed, and other information related to the power supply, whether it is a battery or an external power supply.

The following code shows how to obtain the information.

[C #]

Protected override void OnNavigatedTo (System. windows. navigation. navigationEventArgs e) {var timer = new DispatcherTimer (); timer. interval = new TimeSpan (0, 0, 10); timer. tick + = new EventHandler (a, B) =>{// the number of bytes used in the current memory var x = Microsoft. phone. info. deviceStatus. applicationCurrentMemoryUsage; textblock1.Text = "current Memory:" + convert (x); // The number of bytes used in memory during peak hours var y = Microsoft. phone. info. deviceStatus. applicationPeakMemoryUsage; textblock2.Text = "peak memory:" + convert (y) ;}); timer. start (); textblock3.Text = "device manufacturer name:" + DeviceStatus. deviceManufacturer; textblock4.Text = "device name:" + DeviceStatus. deviceName; textblock5.Text = "firmware version:" + DeviceStatus. deviceFirmwareVersion; textblock6.Text = "hardware version:" + DeviceStatus. deviceHardwareVersion; textblock7.Text = "physical memory size:" + convert (DeviceStatus. deviceTotalMemory); textblock8.Text = "maximum extra memory allocated by the application process:" + convert (DeviceStatus. applicationMemoryUsageLimit); textblock9.Text = "Whether the hardware keyboard is included:" + DeviceStatus. isKeyboardPresent. toString (); textblock10.Text = "whether to deploy the hardware keyboard:" + DeviceStatus. isKeyboardDeployed. toString (); textblock11.Text = "Power status:" + DeviceStatus. powerSource. toString (); // DeviceStatus when the keyboard is disabled or deployed. keyboardDeployedChanged + = new EventHandler (a, B) => {textblock9.Text = "keyboard change, whether the hardware keyboard is included:" + DeviceStatus. isKeyboardPresent. toString () ;}); // DeviceStatus when the power of the device changes. powerSourceChanged + = new EventHandler (a, B) => {textblock11.Text = "Power status change:" + DeviceStatus. powerSource. toString () ;}); base. onNavigatedTo (e);} private string convert (long x) {return Math. round (x/(1024.0*1024.0), 2) + "M ";}

 

Ii. Cameras

There are two types of cameras that can be called: PhotoCamera and PhotoCaptureDevice. Generally, If You Want To support WP7 and use the former for basic camera calls, the latter is used for advanced camera capture.

1. PhotoCamera

We first access the camera through PhotoCamera. we can implement a basic camera with the camera function, including auto focus, Flash, resolution adjustment, and other functions. The following Code demonstrates how to use it.

[XAML]

<Grid x: Name = "LayoutRoot" Background = "Transparent"> <Canvas x: Name = "canvas1" Margin = "0, 0, 800 "Tap =" canvas1_Tap "Width =" 480 "Height =" "> <Canvas. background> <VideoBrush x: Name = "viewfinderBrush"/> </Canvas. background> <TextBlock x: Name = "focusBrackets" Text = "[]" FontSize = "40" Visibility = "Collapsed"/> </Canvas> <ListBox x: name = "listbox1" Margin = "95,394,538, 59" SelectionChanged = "listbox#selectionchanged"> <ListBox. itemTemplate> <DataTemplate> <TextBlock Text = "{Binding}"> </TextBlock> </DataTemplate> </ListBox. itemTemplate> <ListBox. itemContainerStyle> <Style TargetType = "ListBoxItem"> <Setter Property = "Margin" Value = "0, 0, 10, 0"/> </Style> </ListBox. itemContainerStyle> <ListBox. itemsPanel> <ItemsPanelTemplate> <StackPanel Orientation = "Horizontal"> </StackPanel> </ItemsPanelTemplate> </ListBox. itemsPanel> </ListBox> <TextBlock x: Name = "textblock1" Foreground = "Red" HorizontalAlignment = "Left" Margin = "584,22, 10,394 "TextWrapping =" Wrap "VerticalAlignment =" Top "/> <TextBlock HorizontalAlignment =" Left "Margin =", "TextWrapping =" Wrap "Text =" Flashlight: "VerticalAlignment =" Top "/> <TextBlock HorizontalAlignment =" Left "Margin =" 273,394, "TextWrapping =" Wrap "Text =" Resolution: "VerticalAlignment =" Top "/> <ListBox x: Name =" listbox2 "Margin =" 350,394, "SelectionChanged =" listbox2_SelectionChanged "> <ListBox. itemTemplate> <DataTemplate> <TextBlock Text = "{Binding}"/> </DataTemplate> </ListBox. itemTemplate> <ListBox. itemContainerStyle> <Style TargetType = "ListBoxItem"> <Setter Property = "Margin" Value = "0, 0, 10, 0"/> </Style> </ListBox. itemContainerStyle> <ListBox. itemsPanel> <ItemsPanelTemplate> <StackPanel Orientation = "Horizontal"/> </ItemsPanelTemplate> </ListBox. itemsPanel> </ListBox> <Button Content = "Focus" HorizontalAlignment = "Left" Margin = "517,410, 0, 0 "VerticalAlignment =" Top "Click =" Button_Click_1 "/> <Button Content =" photo "HorizontalAlignment =" Left "Margin =" 623,410, 500 "VerticalAlignment =" Top "Click =" Button_Click_2 "/> <TextBlock Width =" 10,434 "x: Name =" textblock2 "HorizontalAlignment =" Left "Margin =, 0, 0 "TextWrapping =" Wrap "VerticalAlignment =" Top "/> </Grid>

[C #]

Public partial class MainPage: PhoneApplicationPage {// constructor public MainPage () {InitializeComponent ();} PhotoCamera photoCamera; Libraries library = new MediaLibrary (); protected override void OnNavigatedTo (System. windows. navigation. navigationEventArgs e) {// determines whether the camera if (PhotoCamera. isCameraTypeSupported (CameraType. primary) {textblock1.Text = "current scene: rear camera"; photoCamera = new PhotoCamera (Ca MeraType. primary);} else if (PhotoCamera. isCameraTypeSupported (CameraType. frontFacing) {textblock1.Text = "current scene: front camera"; photoCamera = new PhotoCamera (CameraType. frontFacing);} else {textblock1.Text = "the device does not support cameras"; return;} textblock2.Text = "the camera is being initialized. "; viewfinderBrush. setSource (photoCamera); // photoCamera when camera Initialization is complete. initialized + = (a, B) => {if (B. succeeded) {this. dispatcher. beginInvoke () => {SupportedFlashModesInit (); AvailableResolutionsInit (); textblock2.Text = "the camera Initialization is complete. ";}) ;}}; // photoCamera. captureImageAvailable + = (a, B) => {this. dispatcher. beginInvoke () =>{ textblock2.Text = "saving the photo. ";}); library. savePictureToCameraRoll (Guid. newGuid (). toString () + ". jpg ", B. imageStream); this. dispatcher. beginInvoke () => {textblock2.Text = "the photo is saved successfully. ";}) ;}; // photoCa upon focus completion Mera. autoFocusCompleted + = (a, B) => {this. dispatcher. beginInvoke () => {textblock2.Text = "autofocus finished. "; focusBrackets. visibility = Visibility. collapsed ;}) ;}; base. onNavigatedTo (e);} // <summary> // display the supported flash mode /// </summary> private void SupportedFlashModesInit () {List <string> flashModes = new List <string> () {""}; if (photoCamera. isFlashModeSupported (FlashMode. on) flashModes. add ("open"); if (PhotoCamera. isFlashModeSupported (FlashMode. auto) flashModes. add ("Auto"); if (photoCamera. isFlashModeSupported (FlashMode. redEyeReduction) flashModes. add (""); listbox1.ItemsSource = flashModes;} // <summary> // display the supported resolutions /// </summary> private void AvailableResolutionsInit () {listbox2.ItemsSource = photoCamera. availableResolutions;} // focus private void Button_Click_1 (object sender, RoutedEventAr Gs e) {// whether autofocus is supported if (photoCamera. isFocusSupported = true) {try {photoCamera. focus ();} catch (Exception ex) {this. dispatcher. beginInvoke () =>{ textblock2.Text = "focus error:" + ex. message;}) ;}} else {this. dispatcher. beginInvoke () => {textblock2.Text = "The camera does not support auto focus. ";}) ;}}// private void Button_Click_2 (object sender, RoutedEventArgs e) {if (photoCamera! = Null) {try {photoCamera. captureImage ();} catch (Exception ex) {this. dispatcher. beginInvoke () =>{ textblock2.Text = "Photo error:" + ex. message;}) ;}}// focus on a specific point private void canvas1_Tap (object sender, GestureEventArgs e) {if (photoCamera = null) return; if (! PhotoCamera. isFocusAtPointSupported) {textblock2.Text = "Focus at specific points is not supported"; return;} try {Point tapLocation = e. getPosition (canvas1); focusBrackets. setValue (Canvas. leftProperty, tapLocation. x-30); focusBrackets. setValue (Canvas. topProperty, tapLocation. y-28); double focusXPercentage = tapLocation. x/canvas1.Width; double focusYPercentage = tapLocation. y/canvas1.Height; focusBrackets. visibility = Visibility. visible; photoCamera. focusAtPoint (focusXPercentage, focusYPercentage); this. dispatcher. beginInvoke (delegate () {textblock2.Text = String. format ("Focus on position [{0: N2}, {1: N2}]", focusXPercentage, focusYPercentage) ;});} catch (Exception focusError) {this. dispatcher. beginInvoke (delegate () {textblock2.Text = "focus error:" + focusError. message; focusBrackets. visibility = Visibility. collapsed;}) ;}}// switch the flashlight mode private void listbox#selectionchanged (object sender, SelectionChangedEventArgs e) {if (e. addedItems. count = 0) return; switch (e. addedItems [0]. toString () {case "off": photoCamera. flashMode = FlashMode. off; break; case "automatic": photoCamera. flashMode = FlashMode. auto; break; case "Redeye": photoCamera. flashMode = FlashMode. redEyeReduction; break; case "on": photoCamera. flashMode = FlashMode. on; break;} textblock2.Text = "the flash mode has been set to:" + e. addedItems [0]. toString ();} // switch resolution private void listbox2_SelectionChanged (object sender, SelectionChangedEventArgs e) {if (e. addedItems. count = 0) return; photoCamera. resolution = (Size) e. addedItems [0]; textblock2.Text = "resolution set to:" + photoCamera. resolution. toString ();}}
2. PhotoCaptureDevice

Many of PhotoCaptureDevice's advanced camera capture methods are used to support later versions. The following is a simple demonstration of how to capture and Display photos through PhotoCaptureDevice.

[XAML]

<Grid x: Name = "LayoutRoot" Background = "Transparent"> <Canvas x: Name = "canvas1" Margin = "0, 0, 800 "Width =" 480 "Height =" "> <Canvas. background> <VideoBrush x: Name = "viewfinderBrush"/> </Canvas. background> <Button Content = "" Canvas. left = "653" Canvas. top = "383" Click = "Button_Click_1"/> <Image x: Name = "img1" Height = "231" Canvas. left = "508" Canvas. top = "87" Width = "220"/> </Canvas> </Grid>

[C #]

Public partial class MainPage: PhoneApplicationPage {// constructor public MainPage () {InitializeComponent ();} PhotoCaptureDevice photoCaptureDevice; inclucameracapturesequence; MemoryStream captureStream = new MemoryStream (); protected async override void OnNavigatedTo (NavigationEventArgs e) {if (PhotoCaptureDevice. availableSensorLocations. contains (CameraSensorLocation. back) {var SupportedResolutions = PhotoCaptureDevice. getAvailableCaptureResolutions (CameraSensorLocation. back); photoCaptureDevice = await PhotoCaptureDevice. openAsync (CameraSensorLocation. back, SupportedResolutions [0]);} else if (PhotoCaptureDevice. availableSensorLocations. contains (CameraSensorLocation. front) {var SupportedResolutions = PhotoCaptureDevice. getAvailableCaptureResolutions (CameraSensorLocation. front); photoCaptureDevice = await PhotoCaptureDevice. openAsync (CameraSensorLocation. front, SupportedResolutions [0]);} else {return;} viewfinderBrush. setSource (photoCaptureDevice); cameraCaptureSequence = photoCaptureDevice. createCaptureSequence (1); // Set camera properties. photoCaptureDevice. setProperty (KnownCameraPhotoProperties. flashMode, FlashState. on); photoCaptureDevice. setProperty (KnownCameraGeneralProperties. playShutterSoundOnCapture, true); photoCaptureDevice. setProperty (KnownCameraGeneralProperties. autoFocusRange, AutoFocusRange. infinity); cameraCaptureSequence. frames [0]. desiredProperties [KnownCameraPhotoProperties. sceneMode] = CameraSceneMode. portrait; cameraCaptureSequence. frames [0]. captureStream = captureStream. asOutputStream (); await photoCaptureDevice. prepareCaptureSequenceAsync (cameraCaptureSequence); base. onNavigatedTo (e);} public async void Capture () {await cameraCaptureSequence. startCaptureAsync (); var B = new BitmapImage (); B. setSource (captureStream); img1.Source = B;} private void Button_Click_1 (object sender, RoutedEventArgs e) {Capture ();}}

 

3. Compass Sensor

The compass sensor is used to perceive the Earth's magnetic field. It is mainly used to determine the direction. With it, we can develop applications similar to the compass.

Not every device must support the compass sensor, so we need to determine whether the device supports it before use.

[C #]

If (! Compass. IsSupported) {MessageBox. Show ("the device does not support Compass"); return ;}

 

If the device supports this function, we also need to determine the accuracy of the compass. If the precision is not high, we need to remind the user to verify the accuracy. When the compass acquires data, it processes the obtained data through the CurrentValueChanged event.

[XAML]

<Canvas x: Name = "canvas1" Background = "Black" Visibility = "Collapsed"> <Image x: Name = "image3" Canvas. top = "12" Canvas. left = "70" Source = "Image/3.png"/> <TextBlock TextWrapping =" Wrap "Width =" 450 "Canvas. top = "240" Text = "your compass needs verification. Please move your mobile phone as shown in the following way. The system will automatically complete the verification process. "/> <Button Content =" completed verification "Canvas. Left =" 154 "Canvas. Top =" 596 "Click =" Button_Click_1 "/> </Canvas>

 

[C #]

Compass = new Compass (); // specifies the data update interval. compass. timeBetweenUpdates = TimeSpan. fromMilliseconds (20); // compass occurs when data is obtained from the compass sensor. currentValueChanged + = new EventHandler <SensorReadingEventArgs <CompassReading> (compass_CurrentValueChanged); // compass occurs when the compass needs to be verified. calibrate + = new EventHandler <CalibrationEventArgs> (compass_Calibrate );
Compass. start (); // void compass_CurrentValueChanged (object sender, SensorReadingEventArgs <CompassReading> e) occurred when obtaining new data from the sensor {// obtain trueHeading = e. sensorReading. trueHeading;} // void compass_Calibrate (object sender, CalibrationEventArgs e) {Dispatcher. beginInvoke () => {// The compass needs to be verified. canvas1 indicates that the user verifies canvas1.Visibility = Visibility. visible ;});}

 

Iv. Accelerometer

The accelerometer is used to test the attitude of a device in space at a certain time point. It is related to gravity. Its values are divided into three directions: x, y, and z. The following describes the meanings of these values. We assume that the front of the device is lying on the horizontal desktop as a reference:
X: the larger the device's left tilt trend, the smaller the value. When the left tilt is 90 degrees, the value is-1. On the contrary, the larger the right tilt value is, the maximum value is 1.
Y: The larger the device's leaning trend, the smaller the value. When the leaning is 90 degrees, the value is-1. On the contrary, the larger the value is, the maximum value is 1.
Z: the larger the trend of equipment downtilt, the larger the value. When the downtilt is 180 degrees (over), the value is 1; when the front is up (not moving), the most-1.

In general, x controls the left and right, y controls the front and back, and z controls the upper and lower. Next we will look at how to use it.

 

[C #]

// Check whether the device supports if (! Accelerometer. isSupported) {MessageBox. show ("the device does not support gravity sensing");} var accelerometer = new Accelerometer (); accelerometer. timeBetweenUpdates = TimeSpan. fromMilliseconds (20); // accelerometer occurs when the data is obtained from the accelerometer. currentValueChanged + = new EventHandler <SensorReadingEventArgs <AccelerometerReading> (accelerometer_CurrentValueChanged); accelerometer. start (); // void accelerometer_CurrentValueChanged (object sender, SensorReadingEventArgs <AccelerometerReading> e) when obtaining data from the accelerometer {// obtain the acceleration vector vector3 = e. sensorReading. acceleration ;}

 

V. Gyroscope

Gyroscope is used to detect the rotation trend of devices in space. Its three values are the rotation speed of the device around the three axes.
X: horizontal left and right axis rotation speed.
Y: the rotation speed of the horizontal forward and backward axes.
Z: the vertical axis rotation speed.

Then let's look at how to call the gyroscope.

[C #]

// Determine whether the device supports gyroscope if (! Gyroscope. isSupported) {MessageBox. show ("the device does not support gyroscope");} Gyroscope = new gyroscope (); gyroscope. timeBetweenUpdates = TimeSpan. fromMilliseconds (20); // gyroscope occurs when data is obtained from the gyroscope. currentValueChanged + = new EventHandler <SensorReadingEventArgs <GyroscopeReading> (gyroscope_CurrentValueChanged); // starts the gyroscope. If it fails to be started, you need to capture gyroscope exceptions. start (); // when the data obtained from the gyroscope is void gyroscope_CurrentValueChanged (object sender, SensorReadingEventArgs <GyroscopeReading> e) {// get the rotation speed of the device around each axis var rotationRate = e. sensorReading. rotationRate ;}

 

6. How to vibrate mobile phones

Mobile phone vibration can be achieved through a simple API. In some cases, you may need to set the world of vibration and terminate the vibration ahead of schedule. The following code demonstrates how to perform the operation.

[C #]

VibrateController testVibrateController = VibrateController. Default; // defines the vibration time testVibrateController. Start (TimeSpan. FromSeconds (3); // stops the vibration testVibrateController. Stop () before the vibration time reaches ();

 

Author: [Lipan]
Source: [http://www.cnblogs.com/lipan/]
Copyright: The copyright of this article is shared by the author and the blog. The source and author of the original text must be indicated during reprinting, and the original text point-to-type link must be retained. The original content cannot be changed. Otherwise, the author will be held legally liable. Previous Article: Windows phone 8 study notes and multi-task
Series directory
Next article: Windows phone 8 learning notes positioning map navigation
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.