理解 Windows Phone 8 的传感器 API 已翻译 100%

oschina 投递于 2013/06/05 06:34 (共 13 段, 翻译完成于 06-06)
阅读 776
收藏 1
1
加载中

Introduction

While theAccelerometer,Compass,Gyrometer, andMotionsensors each return different types of data, they each implement the same pattern for reporting their data. Over the next several pages, you’ll learn techniques that are useful for reading data from any of the sensors. We show you these techniques as you build the foundation of the sample application. The classes and interfaces that comprise the Sensor API are found in theWindows.Devices.Sensorsnamespace.

Note In the Windows Phone 8 SDK there are two separate Sensor APIs. The APIs found inMicrosoft.Devices.Sensorswere originally part of the Windows Phone 7 SDK and have been brought forward to Windows Phone 8. The second Sensor API, found in theWindows.Devices.Sensorscomes from the Windows 8 Runtime that the Windows Phone shares with the Windows 8 operating system. If you intend to share code between Windows Phone and Windows 8 applications, you should consider using the Windows 8 Sensor API. The Windows Phone 7 Sensors API is not covered in our book.

已有 1 人翻译此段
我来翻译

Even though theAccelerometer,Compass,Gyrometer,InclinometerandOrientationSensordo not share a common base class, the all have a number of identical properties, methods, and events. These common members are described in table 1.

Table 1 Common sensor class members

Member Type Description 
GetCurrentReading Method Returns a read-only object containing the currently available sensor data.
GetDefault Method A static factory method that returns a sensor instance.
MinimumReportInterval Property A read-only value specifying the smallest value that can be passed set in theReportIntervalproperty.
ReadingChanged Event An event raised when ever the current reading changes.
ReportInterval Property Specifies how often the sensor reads new data. The data returned by theGetCurrentReadingwill only change once every time interval.

An application obtains the current sensor reading by calling theGetCurrentReadingmethod. Alternatively, an application can subscribe to theReadingChangedevent to receive a sensor reading only when the sensor has new data. TheGetCurrentReadingmethod may be called even when the sensor isn’t ready, but the value returned may be null.

Note If theID_CAP_SENSORScapability isn’t present in the WMAppManifest.xml file, calls toGetDefaultfor any will result in aUnauthorizedAccessException. 

已有 1 人翻译此段
我来翻译

Each of the sensor classes defines a static method namedGetDefault. TheGetDefaultmethod allows a developer to determine whether the sensor hardware is installed on a particular device and whether the sensor is available to the application. If the device does not have a particular sensor installed and available, the GetDefault method for the missing sensor returns null.

The Sensor API handles fast application switching on its own. Developers don’t need to unhook the sensors when the application is switched from the foreground. Unlike the camera, sensors automatically resume and don’t provide an explicit restore method. When the application is resumed, the sensors and events are reconnected and data starts to flow again. Before you learn how to work with the data flowing from the sensors, you need to understand how the sensors report data in three dimensions.

已有 1 人翻译此段
我来翻译

Data in three dimensions

Each of the sensors reports data relative to the x, y, z coordinate system defined by the Windows Phone device. The device’s coordinate system is fixed to the device, and moves as the phone moves. The x axis extends out the sides of the device, with positive x pointing to the right side of the device, and negative x pointing to the left side of the device. The y axis runs through the top and bottom of the device, with positive y pointing toward the top. The z axis runs from back to front, with positive z pointing out the front of the device. Figure 1 shows the x, y, and z axes from three different views of a phone.

Figure 1 The x, y, z coordinate system as defined by a Windows Phone

The coordinate system used by the sensors doesn’t necessarily match the coordinate system used by other APIs. One example is the coordinate system used by XAML. In portrait mode XAML, the y axis points in the opposite direction, with positive y pointing out the bottom of the device. Now that you understand the coordinate system used by the sensors, let’s take a closer look at reading data from the sensors.

已有 1 人翻译此段
我来翻译

Reading data with events

Each of the sensors supports an event-driven interaction model with theReadingChangedevent. TheReadingChangedevent sends an event args class instance to an event handler, where the type of event args class varies with each sensor. TheAccelerometersends anAccelerometerReadingChangedEventArgs, the Compass sends aCompassReadingChangedEventArgs, etc.

TheReadingChangedevent handler is called on a background thread. If the event handler updates the user interface, the update logic must be dispatched to the UI thread. The following code snippet shows an example that handles theReadingChangedevent from theGyrometersensor:

void sensor_ReadingChanged(object sender,
    GryometerReadingChangedEventArgs e)
{
    GryometerReading reading = e. Reading;
    Dispatcher.BeginInvoke(() =>
    {
        // add logic here to update the UI with data from the reading
        ...
    }
}

The Sensors sample application we build in chapter 10 of our book does not use theReadingChangedevent. Instead the sample application polls for data using theGetCurrentReadingmethod.

已有 1 人翻译此段
我来翻译

Polling for data

An application doesn’t need to wait for the sensor to raise an event to ask for data. Each sensor exposes data through theGetCurrentReadingmethod. TheGetCurrentReadingmethod can be called whenever the application data determines it needs new data. For example, the reading might be initiated from a button click, a timer tick event, or a background worker:

if (compassSensor != null)
{
    CompassReading reading = compassSensor.GetCurrentReading();
    if (reading != null)
    {
        // add logic here to use the data from the reading
        ...
    }
}



You’ll read sensor data from a timer tick event in the sample application. Before we can show you the sensors in action, you need to create a new project and prepare the application to display sensor data.

已有 1 人翻译此段
我来翻译

Creating the sample application

Open Visual Studio and create a new Windows Phone App named Sensors. The sample application will read values from theAccelerometer, theCompass, theGyrometer, theInclinometerand theOrientationSensor. The sample application, shown in figure 2, displays a set of colored bars for data from theAccelerometer, theGyrometer, and theInclinometer. Each set of bars displays sensor readings for the x, y, and z coordinates. At the bottom of the screen, the application displays a legend and informational messages about the sensors, as well as readings from theCompassandOrientationSensor.

Figure 2 The Sensors sample application displays bars representing the x, y, and z values reported by the Accelerometer, Gyrometer, and Inclinometer

When a sensor’s value is positive, a bar will be drawn to scale above the effective zero line. A negative sensor value results in a bar drawn below the zero line. Since the range of possible values differs between each sensor, the height of the bar is transformed from the sensors value into a pixel height using a scaling factor. First, you’ll create a reusable control to display the positive and negative bars.

已有 1 人翻译此段
我来翻译

Creating a reusable Bar control

To simplify the sample application, you’ll build a reusable control that allows you to set a scale factor and a sensor value. When the scale or value properties change, the control should draw the appropriate positive or negative bar, and display the value with a label. The bar control will be implemented using the Windows Phone User Control item template, accessed via the Project >> Add New Item menu. Name the new item Bar. The XAML markup for the new control is shown in the next listing.

Listing 1 Markup for the Bar control

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="1*" />                         #1
        <RowDefinition Height="1*" />                         #1
    </Grid.RowDefinitions>
    <Rectangle x:Name="positiveBar" VerticalAlignment="Bottom" />
    <Rectangle x:Name="negativeBar" Grid.Row="1" VerticalAlignment="Top" />
    <TextBlock x:Name="label" VerticalAlignment="Center"        #2
        Grid.RowSpan="2" Text="0" TextAlignment="Center" />     #2
</Grid>
#1 Divide control into two rows
#2 Center label 

The grid is divided into two halves #1 with each half containing a Rectangle. The first Rectangle displays positive values and the other represents negative values. A label is placed right in the middle #2 to show the bar’s value. Figure 10.3 demonstrates what the control will look like for a Bar with a scale value set to 2.0 and a current value set to −1.0.

Figure 3 A Bar control with a scale value of 2.0 and a current value of -1.0.
已有 1 人翻译此段
我来翻译

Pages that host a Bar control need the ability to set different fill colors for the rectangles. Add a new property namedBarFillto Bar.xaml.cs code behind file:

public Brush BarFill
{
    get { return positiveBar.Fill; }
    set
    {
        positiveBar.Fill = value;
        negativeBar.Fill = value;
    }
}

The setter for theBarFillproperty assigns the specified Brush to both thepositiveBarandnegativeBarrectangles.

Note: If you were building a proper reusable XAML control, theBarFillproperty and the other properties would be dependency properties. The control would declare template parts and would provide XAML markup as the default template. See the book Silverlight 5 in Action for more details on building reusable XAML controls.

Next you create properties to set the scale and value for the bar. Since you don’t know the full range of values, you need the caller to tell the control how to scale the value to the height of the rectangles. Let’s say you need the bar to display a value between 2 and −2, and theBarcontrol is 200 pixels high. A value of 2 would require the positive bar to be a hundred pixels high, whereas a value of −1 would require the negative bar to be 50 pixels high. The next listing details how the bar height is calculated using theScaleandValueproperties.

已有 1 人翻译此段
我来翻译

Listing 2 Calculating bar height with the Scale and Value properties


private double scale;
public double Scale
{
    get { return scale; }
    set
    {
        scale = value;
        Update();                        #1
    }
}
private double barValue;
public double Value
{
    get { return barValue; }
    set
    {
        barValue = value;
        Update(); 
    }
}
private void Update()
{
    int height = (int)(barValue * scale);                  #2
    positiveBar.Height = height > 0 ? height : 0;
    negativeBar.Height = height < 0 ? height * -1 : 0;     #3
    label.Text = barValue.ToString("0.0");   
}
#1 Recalculate when properties change
#2 Calculate height of bar
#3 Invert negative height
Both theScaleand theValueproperties are implemented with backing fields and simple getters and setters. Inside the setter of each property, you call theUpdatemethod #1 to recalculate the height of the bar rectangles and update the user interface. Inside theUpdatemethod you multiply the scale andbarValuefields #2, and the resulting value is the number of pixels high the bar should be drawn. If the calculated height value is greater than 0, thepositiveBar’s Height is updated to the new value. If the calculated height value is less than zero, you invert the calculated value #3 before assigning thenegativeBar’s height. Finally, you use theToStringmethod with a formatting string to set the label’s Text property.


Now that you have a bar control, you can create the sample application’s user interface. You need to add an XML namespace to MainPage.xaml so that you can use your new bar control:

xmlns:l="clr-namespace:Sensors"

You’re now ready to use the Bar control in the MainPage’s XAML markup. You need to design the MainPage to have three Bar controls for each sensor, for a total of nine Bar controls.

已有 1 人翻译此段
我来翻译
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接。
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
加载中

评论(3)

MtrS
MtrS
原文更新了,换成了“如何精心设计一个Windows 8 WinRT的应用”,
但是链接过去的图片地址没变,配图与文章内容就不匹配了,

建议 将英文配图换成中文中的配图。 @红薯
红薯
红薯

引用来自“MtrS”的评论

@红薯 配图与 文章不符啊,打开原文 链接 也不是“创建Windows Phone 8 的传感器应用程序” 越翻译越感觉 配图与文字 相去渐远 @红薯

原文的图啊
MtrS
MtrS
@红薯 配图与 文章不符啊,打开原文 链接 也不是“创建Windows Phone 8 的传感器应用程序” 越翻译越感觉 配图与文字 相去渐远 @红薯
返回顶部
顶部