一本关于用C#开发Android的参考教程,Xamarin公司首席技术官推荐作序《C#开发Android应用实战—使用Mono for Android和.Net/C#》Xamarin Mobile developmentBJared dicksona project submitted in partial fulfillment of the requirements for the degree ofMaster of science inComputer Information SystemsatGrand valley state UniversityDecember 2013Dr robert adamsDecember 201320f17Table of contentsAbstract1. ntroduction2. Cross-Platform Mobile Development Approaches2.1 Native52.2 Mobile web。2.3 Hybrid2.4 Cross-Compiled3. Amarin3.1 Hardware features3. 2 Code Sharing.3.3 Native Bindings…………………67888893. 4 Performance3. 4.ioS3. 4.2 Android04. Experiments.…,104.1 Geolocation104.2 Bluetooth4.3 Shared Libraries124.4 Native bindings……………………………………………………135. Analysis and conclusions……………………………………………………,145.1 Technical issues.5.2 Business value5.3 Summary............1.1..1.115Bibliography.……….…………………………….…………………1630f17abstractMobile application development is a diverse environment and requires specific languages and tools. This makesdevelopment across multiple platforms time and cost intensive. Many solutions have been presented to address theissues of cost and diversity, though none come without their own set of compromises. This project studied Xamarinas a mobile platform development tool allowing for cross-platform development that utilizes a single programminglanguage, native UI elements, code sharing for reuse, and near-native performance. Specifically, we examinedXamarin's support for geolocation, bluetooth, shared libraries and native bindings. Analysis showed that Xamarin isot an answer for all problems, but a solid solution for the appropriate use1 IntroductionMobile interactions happen on a variety of different platforms and devices utilizing their own operating systemsuser-interface designs, app stores, hardware feature sets, device form factors(size), permission implementations, andsoftware development toolkits. This diversity is only increased by the constantly expanding pool of hardwarecomponents and overall device design improvementsOne of the problems in mobile development is that of end-user isolation. The choice of platform, required featuresand operating system backwards compatibility segments users into groups which often limit the growth of theapplication user-base. To combat this there are a limited number of options available The first solution was to rewritethe entire mobile application independently for each platform. This of course leads to high development andmaintenance costs for these applicationsSeveral ideas, products and frameworks have presented themselves in an attempt to simplify and centralizedevelopment in the mobile environment. Mobile websites allow for web content to be created in a way that isspecifically designed for smaller devices. The native approach is often still used by those desiring a native look andfeel, or when high performance is required. Hybrid frameworks have also been designed to allow developers topackage websites into an application while offering interaction with a specific hardware device feature-set, such asGPS or camera functionalThe solution being presented in this paper is called Xamarin. Unlike other options, Xamarin offers developers a wayto create cross-platform applications without sacrificing native UI elements or performance, while allowing code reusebetween platforms. This is done through unifying development to a single programming language, C#. It utilizes theMono runtime which has been developed to bring the C# language to Linux and Macintosh. This creates a singleenvironment for developers to write mobile applications for multiple platforms4of172. Cross-Platform Mobile Development ApproachesMobile development approaches include items such as native, mobile web, hybrid and cross-compiled2.1 NativeThe process of porting mobile applications across a variety of platforms is a time-intensive task. Each of the threemain platforms uses a different programming language. Apple devices running iOS are written using Objective-C asthe primary language. Android devices use Java as the default programming language. Windows Phone uses C#areit's main language. Having developers learn a new language for a specific platform can be very time consuming. Thealternative, of bringing on new developers already fluent in the other platforms, can be costly to a business. When adecision is made lo add a new feature to the existing application there will be a time delay belween launching the newfeature on the different platformsMobile applications that are CPU intensive are often directed towards a native implementation as it will give you thebest performance over the present options. One of the more obvious candidates for a native implementation aregames. Intense graphics processing required by games is not suitable for solutions like Java Script. Complex dataobject models which change frequently should also be implemented in a native solution. Graphs and datarepresentation visuals can sometime be accomplished using JavaScript, but as the number of data points grows theperformance will begin to choke. If a solution is needed that will render a thousand or more data points, one shoulduse a native buildEach of the major platforms provides a guide for best practice design principles. Android recommends placing yourmenu on the bottom of the screen. Whereas ioS positions user menus on the top of the screen. Theseimplementation patterns are beneficial in creating apps that look and feel comfortable to the end user. It assists themin feeling as if the application is an extension of their device instead of a foreign object. This can improve userretention rates over competing applicationsStaying native in mobile applications also provides for a better touch interaction experience. Gestures, pinches andswipes work exactly as they were intended to. Users don' t get as frustrated interacting with the content because theobject responses are intuitive, or at least consistent across the device. Not having an intermediate layer keepsrformance uppreventing touchStudies have been done that give evidence to the idea that going with a native UI helps to increase the retention rateof users in mobile applications. In part, this is because the user already feels familiar with the components of a native5of17application. The user isnt left confused in how to interact with Ul objects. Non-native platforms can sometimes leavethe user guessing how different objects will react to their touches and gestures. Of course, this can be mitigated witha well designed UI2.2 Mobile webThe first push of cross-platform mobile development has been through the use of mobile web. all modernsmartphones come with a capable web browser. With the development of the responsive web through HTML5, CSS3and JavaScript mobile phones have gained powerful tools of interaction. It provides a great platform in terms offlexibility but fails to meet expectations when it comes to the always-on mentality of mobileit becomes accessible to users. Web developers are also able to develop quickly using skills practiced daily o lerDevelopers are able to push immediate updates to users through mobile web. Once the code is up on the web servernormal websites. It takes advantage of an existing infrastructure and comes with an existing level of familiarityThere are practical performance limitations that prevent mobile websites from being commonly used for interactionswith dynamic information However these same limitations are more resilient with static data service interruption andpoor signal can prevent mobile websites from being accessible to users when they need information. If a networkconnection isn't present, then the mobile websites will not be available. Unless data is cached, a user will be requiredto reload all data each time they visit the website. Load times are high because of cell phone network latencyResponsiveness of a mobile website can also be limited by the slow performance of Java Script on mobile devices. Itis normal to expect to see speeds to be lowered by a factor of 10 when JavaScript is moved from desktop to mobile. Inthe event that the web server goes offline for maintenance or malfunction users will be unable to access theinformationDevelopers are also restricted to the level of hardware interaction that is supported by HTML5 and the browserDepending on your application this could be a deciding factor Features such as camera usage and theaccelerometer arent browser capable. Geolocation is supported by some mobile browsers and can be used by mobileweb2. 3 Hybrid WebThe idea ofhybrid applications was born through crossing mobile web applications with native applicationpackaging. It takes advantage of the existing skills of web developers allowing them to write applications usingHTML5, CSS3 and JavaScript. In addition, developers are able to access native hardware and features through aPi6of17calls define by the wrapper. One of the most prominent of these frameworks used today is Phone Gap. It allowsinteraction with GPS, camera, compass, accelerometer and moreThis creates a great opportunity for the mobile development community as a whole. It brings new possibilities to lightthat were not available previously. a web developer can become a mobile application developer without needing tolearn all of the intricate details of the various mobile platformsSince hybrid applications are rendered through the browsers, it isnt possible to use truly native UI components. Adeveloper can use CSS3 techniques to style different UI components to effectively look identical to native UIcomponents, but true duplication isnt possible. This is because you are not able to recreate the responsiveness ofnative Ulelements. It is common that due to this lack of native Ul support many developers have decided to createtheir own styles for their apps. This unique styling causes the mobile application to stand out, and can enable acreative branding which can assist in promoting the applications popularity in some circlesAnother compromise of any hybrid application is the delay that exists between when a new feature comes out to amobile device, and when it is re-implemented for hybrid. Depending on the popularity of the feature, it could take along time before it becomes accessible. This delay is not something you will find in Amarin. However, many suchplatforms allow you to create your own plugins, enabling you to implement the bridge to the new feature on yourown time for each of your target platforms2. 4 Cross-CompiledThe method of developing cross-platform mobile applications in a single compiled programming language is calledcross-compiling. It allows a developer to write an application in one language, and compile it independently for eachtargeted platform. This unification is generally helpful in reducing the amount of development time required to buildmobile applications, as much of the code will be similar. Depending on the platform, native UI elements may or maynot be accessible. Performance is better than hybrid applications, but not al ways as good as native implementationsA performance if often taken because there are many required libraries which need to be loaded into memory by theframework that is being used. Many such solutions also require a monthly developer fee as they are still beingdeveloped and improvedXamarin falls into this category of mobile development. All the code is written in C# and deployed to multipleplatforms. It is based on the Mono runtime which was initially release in 2004. and is still in active development3. AmarinAmarin is a cross-platform mobile application development solution that creates aunified environment for developers. Instead of writing code in Objective-C for iOS andJava for Android, it enables developers to write code in the C# language Eachapplication implementation is developed independently through a platform specificproject in order to preserve native user interfaces. Within each application is directaccess to the native APIs, allowing developers access to all the native hardwarefeatures. Between these projects you can re-use core code common to each application by using portable classlibraries(pCl's)or other methods. This would include items such as data models, business logics, cloud integrationsand database access. If a project requires use of a library written natively, a developer can create a native bindingwhich allows access to it through Ct calls. The performance you receive in Amarin applications is quite close tonative speed, and in certain situations can perform better. On average, Xamarin mobile applications can reuse 75% oftheir code between projects. Once development is complete, each project can be compiled and deployed to theappropriate app store3.1 Hardware FeaturesThe nature of the development of Amarin lends itself to not impose any limits on the availability of the devicehardware to mobile application developers. Amarin generates a native binding directly to the iOS and androidSDK'S. This provides a direct and identically matching link between the Xamarin libraries and the native APIs. Allnative objects are accessible using the same names, with the same properties and attributes, while having the samemethod calls. There is no re-implementation of code in Amarin. All native calls are run through native APIs. GPSaccelerometer, camera, compass and all of the rest are accessible. The process allows Xamarin to release same-dayupdate releases. One of the most published updates was that of same-day support for ioS 73.2 Code SharingPortable Class Libraries, or PCLs, allow developers to write compiled libraries for sharing with multiple projectsOfficial support for PCL is one of the newest releases from Xamarin. Previous options available included file linkingloned project files, and Microsoft Project Linker. All of these methods provided a means of sharing class structuresbetween projects. Depending on the code sharing route, extra steps may have to be taken to be setup correctlybecause much of it was a manual process Writing a single library for a particular core project is the simplest avenueavailable for code sharing, and requires the least amount of maintenance8of173.3 Native BindingsNative bindings are a mechanism available to iOS and Android projects that allow you access native libraries fromwithin your Xamarin mobile application. This is done by creating a binding, or a mapping, of the calls from the C#library to the native library. It is a semi-automated process. Xamarin is able to create many of the connections, butdoes leave some loose ends for the developer to tie upOne of the benefits of using native bindings is that it allows you to incorporate externally written libraries. This cansave developer time in preventing the re-writing of important code. For example, optical character recognition(OCR)could be a requirement of a mobile application. Instead of writing all of the ocr code a developer could includethrough native bindings, open source library packages to add extra functionality3. 4 PerformanceC+ARMNETAOTAPP DistributionBinaryBindingsRunsNativelyC+Android NET Compile, DistributionBindingsRunsNative3.4.1ioSC# code for iOS in Xamarin compiled to a native ARM binary. This allows Xamarin ioS mobile applicationsperformance to be on par with their Objective-C based counterparts. The process involves compiling the applicationusing the same LL VM Engine used by XCode9of17