Как создать приложение на андроид в visual studio
Перейти к содержимому

Как создать приложение на андроид в visual studio

  • автор:

 

Using Visual Studio Code for Android Development

First, why do you event want to do this when Android Studio is already a fully capable IDE available on all platforms. Here’s some reason :

To do realtime remote pair-programming session with actual collaborative-editing and shared build/test. This is something you cannot do (yet) with Android Studio. On the other hand, VSCode has a great support for it through Live Share Extension. So, being able to work with your project in VSCode automatically give you that capability.

More lightweight, casual use case. Android Studio, with IntelliJ being its base, is notoriously heavy. That is fine if you are in the development mode where you need many of all its integrated capability. However, there is a case, like where you are mostly working with more internal and logic code with less need of UI matter, you need only very common tooling related to unit-test, code, refactor cycle. On the later case, VSCode has much all you need without being as resource-demanding and you can launch and work more conveniently.

That just some major ones of the reason you might want to set it up. There are some other benefits that also interesting to look at. Like, getting access to rich VSCode extension ecosystem. As like Live Share extension mentioned above, you can also make use of some other interesting extensions like GitLens where you have rich git-related annotations right on the editor or Todo+ which is quite fun and geeky way to track your ever-growing task while you code with nothing but text file.

Complementary Nature

This surely not meant to actually replace Android Studio as your main IDE but to complement it instead. A way of adding capabilities that you need that is not available on it natively. Beyond what you need from VSCode specifically above, like doing remote pairing for example, you’d better use Android Studio for the rest.

So, feel free to stick with Android Studio and only pickup VSCode for those rare times you actually need to.

The Setup

Beyond the base VSCode install, here are some extension you need to install :

    . This add the typical language support like syntax highlighting and formatting. There is extension that is already exist longer with more install number related to Kotlin but I find this one has more feature and already a good amount of installs . For Graddle support, obviously . This one is the interesting one. As we’ll see later, this makes working with Android project can still be quite convenient even though we are outside Android Studio with all its various shortcuts and automation

Apart from that you can install other extension based on your specific needs like LiveShare mentioned above if you meant to do remote pair programming with it, or install vim editing support if you are into it.

Gradle Pinned Task

With Gradle Task you’ll get access to gradle tasks as a nice navigable tasks on the sidebar. That is already interesting in itself but what is even more useful is that you can pinned the task you often need to the Pinned Task section as highlighted on the screenshot below, a kind of favorite list, complete with saved custom arguments that you want to pass to it.

This makes accessing any repeated command very convenient and fast.

Understand Command Line Counterpart of IDE Interface

Directly calling gradle task as above means you need to get familiar with the command line counter part of the action you usually do through Android Studio interface like from buttons or shortcuts. The below resources could help to map it out. As a side benefit, you’ll gain more knowledge of the platform itself in the process.

    . Quite complete list of things related to android testing including how to run commonly used task from command line . Quite long and exhaustive, you can find even more here

After you know the command line you can use directly it on the built-in terminal or setup a Gradle Pinned Tasks as mentioned above.

Below is the example of the task run on the built-in terminal.

The good thing about it is run in such a direct manner on just the terminal means your remote pair, if you use Live Share, will have access to the same command and terminal also. This means you can switch who drives the pairing session, for both editing and running the test, at any time instantly.

So, that’s it, it is a relatively simple setup for quite a number of useful features, especially if you in need for the things that it provides like real time collaborative editing/running.

Build a Basic Android App with Xamarin and Visual Studio

Build a Basic Android App with Xamarin and Visual Studio

Are you a .NET developer that has always wanted to make a mobile application? Or maybe you have tried building native mobile apps with Android or iOS but didn’t like the languages? Well then, you are in luck! The .NET world has been blessed with Xamarin; a set of tools that lets you build mobile apps for Android, iOS, and Windows within Visual Studio.

Xamarin has two main flavors: Xamarin platform (Xamarin.iOS and Xamarin.Android) and Xamarin.Forms. With Xamarin.Forms a vast majority of your business logic and user interface can be written within one shared project that produces fully functioning apps on all 3 of the iOS, Android and the Windows (UWP) operating systems. Xamarin platform, on the other hand, is very much platform-specific work and is more akin to writing native apps but with C#.

In this tutorial, I’ll be looking more closely at the Xamarin platform and the Android operating system toolset known as Xamarin.Android. The overall aim is to enable you to create a simple native Android app with basic user authentication included.

Set Up Visual Studio and Your Environment

To follow along you’ll need a copy of Visual Studio, plus the ‘Mobile development with .NET’ workload. You can either enable this feature from first installation of Visual Studio or access it from the ‘Tools -> Get Tools and Features…’ menu item:

Visual Studio Installer

When testing and running your app you have the choice of doing so with either an Android emulator running on your development machine, or by directly connecting to an existing Android device. There’s no right option here and different developers prefer different form factors. If you choose the former option, you’ll need to ensure once you’ve selected the workload that on the right-hand pane (‘Installation details’) the checkboxes for Intel Hardware Accelerated Execution Manager and Google Android Emulator are selected (as seen above).

Verify Your Android Environment in Visual Studio

To verify everything installed properly and was configured correctly, go to ‘Tools -> Options -> Xamarin -> Android Settings’ and check your Java Development Kit Location and Android SDK Location paths are valid (i.e. have a green tick):

Visual Studio Android settings

If either are missing you’ll have to manually install the Java Development Kit or Android SDK respectively.

Create a Xamarin App

Start by creating a new project and select the ‘Android App (Xamarin)’ master template (found under the Android menu). On the next page you’ll want to pick the ‘Single View App’ option as it is a great starter template to work from.

With regards to the Minimum Android Version, this is something down to your personal choice as the developer. There is a trade-off here between being able to access the latest and greatest API features in newer versions and supporting your customers that have older versions. To help you make this decision, Google publishes platform version distribution data they collect as part of their Distribution dashboard on a fairly regular cadence. My personal preference is between 5.0 or 6.0 depending on if this is an app for public consumption or a commissioned app for corporate phones only (i.e. they will likely have the latest updates); in this example I’ve gone with the latter. Note this version differs from the Target Android Version and that should always be set to the latest released SDK version, as anything less won’t be accepted into the Google Play store.

Once you’ve got this created all that’s left is to import the required NuGet packages. For this tutorial you will need:

  • Xamarin.OpenId.AppAuth.Android — To Authenticate the user you will be using OpenID Connect standard (an enhancement of OAuth 2.0). The easiest way to implement client code that abides by this specification is by using the AppAuth client SDK for Android, and helpfully Xamarin has ported a package of this functionality available for you to use.
  • System.IdentityModel.Tokens.Jwt — The method of authentication here uses JSON Web Tokens. To extract the data needed from these tokens you’ll need this package.

Additionally, you’ll need these two packages as well as they’re relied upon by AppAuth:

  • Xamarin.Android.Support.v4
  • Xamarin.Android.Support.CustomTabs

Familiarize Yourself with the Xamarin Project

If you’ve never worked with Android before, one of the key principles to get your head around is the concept of an Activity. Activities are components used to display your user interface; in their most basic form, you can think of Activities as being equal to pages in an app that the user can navigate between. An Activity in code is represented by a class, however like a page in ASP.NET you can (and almost always will) associate an XML-based layout file (a .axml file) with it for a displayable design. All new projects create a ‘MainActivity.cs’ and ‘activity_main.axml’ file to start with as the first Activity (i.e. page) to run upon opening the app. This can be changed to any other Activity by utilisation of the property MainLauncher = true within the Activity attribute of the class.

Visual Studio folder structure

Resources are designed to be handled within their own directory and follow a somewhat strict naming convention. I’d strongly recommend storing as much of your resources as is feasible in this directory since it simplifies the reuse of these variables for your ongoing development. In the ‘values’ directory of the Resources directory is where you will find files with specific purposes:

  • Strings.xml — Hosts all user facing strings. This one is especially important to use as it enables you to localise your strings for a global audience.
  • Styles.xml — Where you’ll find the attributes for styling your design objects; think of it like a CSS file.
  • Colors.xml — A place to store references to the colours you use most frequently as part of your styling.
  • Dimens.xml — As the name might imply, where you define set dimensions for your app’s layout.

The other notable directories don’t follow any naming convention for their files, but they must contain certain file types:

  • Layout — Location for storing your .axml files. These files define full Activity layouts, layout components that you programmatically generate and populate, layouts of dialog (alert) boxes, etc.
  • Menu — Where you’ll find definitions of menus and their items. These are .xml files that have menu as the root element and item child elements, of which can be grouped together with group elements. Most common menus you’ll encounter are the overflow menu (from the three vertical dots button) or the navigation menu (from the home ‘hamburger’ button).
  • Mipmap — Where you want to define images that need to be scaled depending on the screen density, i.e. those referenced by other apps, and not used internally. The app’s icon is the most common content you would put in the mipmap directories.
  • Drawable — Not standard in a default project template, but can be created yourself. This is where you store your images/drawable content to be used within the app, e.g. splash screen, custom progress bar designs, icons used within the app, etc.

Lastly, if you have any raw content files that you want to use as part of your application (e.g. a text or font file), then the Assets directory is where to place them. As Assets these files will be deployed with your app for you to access with the Asset Manager.

To learn more about Assets and Resources and how to use them, there are handy ‘About’ text files in each directory of a newly created project.

Add User Authentication to Xamarin with OpenID Connect

Most apps these days require some form of user identification to enable the developer to offer bespoke experiences and in turn enable the user to keep their data across devices/installations. In addition to this there’s the matter of access control that might be useful to authorize a subset of users for extra functionality. Naturally this can be quite the laborious task, especially if you’re in the business of creating apps and you’ll need a new system for every single one. Thankfully with Okta you can set up an application in mere minutes and then all the hard work is done for you! The Okta service is OAuth 2.0 compliant and a certified OpenID Connect Provider, and so works perfectly with the AppAuth client SDK for all your authentication and authorization needs.

Set Up your Okta Application

Firstly, you should set up a new application in your Okta account for this project. If you’ve not got one yet, it’s really easy to create a new forever-free developer account.

Once that’s complete and you’ve logged in to the developer dashboard, take a note of the Org URL as we’ll need that later:

Okta Org URL

From the dashboard go to the ‘Applications’ tab and from there ‘Add Application’. You’re creating a native Android application, so it’s best to pick the ‘Native’ platform template.

From this page add a name for your application and leave everything else as default. Once saved take note of your Login redirect URIs and Client ID as you’ll be needing these next.

Okta application settings

So you can use these three values from Okta with ease in the future, I would recommend putting them in their own static class within a new directory for the authentication logic:

Create the Authentication Provider

Let’s get the boilerplate code out of the way. You need to configure the app to inform it of your redirect URI scheme. The scheme is your login redirect URI (in standard reverse domain name form) without the path. For example, from the above screenshot my scheme would be ‘com.oktapreview.dev-123456’.

The easiest way to do this is to insert the below intent filter snippet into your AndroidManifest.xml file in the Properties folder of your solution. Add the following XML within the Application tag and change the scheme value to your own:

You also need to define the model for the result of your authorization with a simple class. While I won’t be using all the values I’ve written below within the code, I will show how to populate them for you to use after. As this is part of your application’s model, create a folder called Models and add an AuthorizationResult.cs class inside it. Then, add the following code:

Android doesn’t have a global state for you to work with, and so if you want to pass simple values between activities, the best way to do this is with the Extras functionality on the Intent object. An Intent is a predefined class in Android and another core concept to understand. It is the abstraction of an operation to be performed (i.e. your ‘intentions’), and to navigate forward to another activity you need to create an instance of this class with which activity you ‘intend’ to go to. The Extras properties on the Intent object are in effect just a dictionary of keys to object values and are accessed by Put and typed Get methods.

While these methods keep the usage relatively clear and easy I personally like to keep all access to them within their own class (to be precise, an extensions class), to maintain a better separation of concerns. This is extremely useful as you don’t need to access the keys across classes and can assure type safety when putting and getting these values. In your authorization provider you’ll be wanting to: store the AuthState , be able to check whether it’s there, and return it if it is. Create a new folder called Extensions in the root of the solution. Then add a new class called IntentExtensions.cs . Make the class public and static , then add the following code inside the class:

Now it’s time to define the authorization provider, AuthorizationProvider.cs in the Authentication folder you created before for the Configuration.cs class. Firstly, remove all the using statements inside the newly created class, then declare the configuration as static readonly variables:

The configuration endpoint is a standard in OpenID as the discovery endpoint to find all that’s supported. Note here I’ve written this is using the ‘default’ provider name. If you have a different provider, you’ll want to change this here. Also note that this is using the Android.Net flavour of the Uri class, and not the System version — you’ll need to add the former to your usings or fully qualify the type for this to work. The Scopes variable, like any other OpenID system, defines what we’re authorized to access.

Next you should declare your member variables:

A quick explanation on each:

  • The authorization request and completed intent are parameters created for use in making the authorization call. I’ve written them as global variables here to minimise the amount of passing parameters into different methods.
  • The authorizationState variable as it’s named defines the current given authorization state.
  • The authorizationService variable contains an instance of the authorization service.
  • The context variable here is of the calling activity, so you can reference it when necessary.
  • Finally, the taskCompletionSource enables you to make all these calls asynchronously and then return once complete.

Now you should define the values of these readonly variables in your constructor, and declare the public methods your code will call:

The SignInAsync method is as you might have guessed an asynchronous method to sign a user in. This returns the AuthorizationResult class you wrote earlier. NotifyCallback on the other hand is for the calling activity, once it has returned from the external sign in page, to call back to the authorization provider and let it know it’s done. The sign in method I’ve broken out into multiple subroutines, and looks like this:

In this you have defined the service configuration, built the authorization request and the intent to call once the authorization has been completed, and then await the request of authorization. To build the authorization request is as follows:

The job of this method is to abstract away the AuthorizationRequest.Builder work and create the request. Next you need to build the Intent for once the operation has completed:

The ‘intention’ that you want to perform here is to return to your MainActivity with a new AuthState attached. Lastly in this flow is to deal with executing the request:

As PerformAuthorizationRequest is synchronous and returns void, the code awaits upon the taskCompletionSource member, knowing it will only ever be set once a response has been retrieved. At this very same point you know the authorization state will be populated (if everything succeeded), and so you can return their values as part of the AuthorizationResult.

The second public method NotifyCallback , as I mentioned before, is what you want the MainActivity class to call back on, once your above completedIntent is run. In this method you want to verify the response, update the state appropriately, and if successful, perform a token exchange request:

Here you can see in the fail cases I set the result of taskCompletionSource to false, and that will unblock the RequestAuthorization method above. Also, the PerformTokenRequest method takes in a delegate, ReceivedTokenResponse , to be run once it has completed. This method is as follows:

At this point you should have all the authorization data you need, and so can update the state appropriately (where you’ll find the values to return from the sign in method) and set the result to unblock the taskCompletionSource task.

Implement Authentication into Your Xamarin Interface

As a clean-up if you so wish, feel free to remove all references to the ‘Floating Action Bar’ (also written as ‘FAB’) within the main activity class/axml files as they’re unnecessary bloat at this stage.

To allow the user to sign in you now need to implement this functionality into the UI. Given the default design, the most intuitive way to do this would be to add an item to the overflow menu in the top right corner. You can do this by editing the menu_main.xml file in the ‘Resources -> menu’ folder, and adding this item as a child of the menu tag:

With this code you’ve created a new option with a title to be defined in the string resources file. As mentioned before in Android it’s best practice to put all user facing text in the string resources file. To declare this data, edit the strings.xml file in the ‘Resources -> values’ folder and add these lines:

Not only have I declared a string for the ‘Sign In’ button here, but I’ve also added above a string for a welcome message to the user once they have signed in. The equivalent to the C# code of this string would be “Hi, <0>!”`, where the placeholder is of type string.

Note with all updates to these Resources-based files, the Resource.designer.cs class will automatically be regenerated with new IDs for each object you’ve created, that can be referenced within your code. If this isn’t working for a particular file then select it in Solution Explorer and look at the Properties window. Make sure the CustomTool property is set to the value MSBuild:UpdateGeneratedFiles , as this is likely missing and preventing the designer file from recognising it as a resource.

Next add a ProgressBar to the existing activity_main.axml layout file:

This ProgressBar (or spinner, as the case is), has an ID you can reference with code, and is set up to sit around the centre of the screen. The visibility is set to gone for now, but once your authorization code is running you can set it to visible and inform the user that the app is busy.

Now you have a button to open authentication and a progress spinner to inform the user the app is busy, it’s time to use them. Within your MainActivity class add the following property to the Activity attribute (above the class header):

This property ensures there is only one instance of the MainActivity class, and you don’t keep opening new ones. Once you’ve done this, add a static member variable for the AuthorizationProvder you wrote above and create an instance of it within the existing override of the OnCreate method. Note this should be done after the existing code within the method:

Next, override the OnNewIntent method. The purpose of this is when a new intent of this class is created (i.e. when the external sign in window returns), you call the NotifyCallback method from the AuthorizationProvider . Also included in this is a quick check to make sure it’s the expected flow:

Now add the code behind the menu item you added. In the existing override of the OnOptionsItemSelected method, add an if statement with a call to a new method that will handle the sign in process as follows:

This new method will start by making the ProgressBar you added moments ago visible; to retrieve any component from the layout file, use the generic method FindViewById and enter the component’s ID as its argument. After this, make a call to the SignInAsync method and await its result. Once the call has returned the result is then verified as authorized. If this authorization failed for whatever reason an error dialog appears, and the progress spinner disappears again. I’ll leave detailing the success case for now as you still need somewhere to go in that instance:

When the user is authenticated you should redirect them to the next page of your experience. If you recall earlier each page is represented by an Activity, and so you need to create a new one now.

To start, within the ‘Resources -> layout’ folder you’ll need to create the new activity layout file “activity_dashboard.axml”. The easiest way to do this is by going to the New Item… option in the context menu and selecting the ‘Android Layout’ template. Within your new layout file add a simple TextView component to display text like this:

In this snippet you have a TextView component with a referenceable ID that’s centered in the middle of the page, of which will display a welcome message. Next create a corresponding activity class ‘DashboardActivity’ by means of the ‘New Item…’ option in the context menu from the project in the solution explorer and selecting the ‘Activity’ template. To link this class to its layout file, you need to call the SetContentView function in the generated OnCreate() method (under the inherited base method invocation):

To personalise your welcome message, you’ll want to pass the user’s name to your new activity. If you remember earlier the best way to do this was with Extras on the intent, and you created an extensions class to handle this. Like before, add new methods for ‘Put’ and ‘Get’ of a ‘name’ extra in the IntentExtensions.cs file you created above:

Now using this extended functionality, after the call to SetContentView you did in the OnCreate() method, retrieve the user’s name and set the TextView component’s text appropriately:

In this extract, upon retrieving the TextView instance its value is set to your welcome message, of which is created using the Android Resources equivalent of string.Format() .

With this your dashboard activity is complete, and you now need to call to it. In the placeholder for the success case I left open from the OnSignInAttempted method, you can achieve this by adding the following code:

The first block reads the token and retrieves the user’s name (if it exists). In the second a new Intent is created for the dashboard activity, the user’s name is stored in this Intent using your above-defined extension method, and then the activity is started (i.e. navigated to). To prevent the user from navigating back to this page afterwards, the code ends by calling the Finish() method.

Run Your Android App

Now it’s time to launch your application using your chosen device!

If you’re debugging using the emulator this should be as simple as hitting F5 of which will first open and load the emulator, and then the code will deploy to it. As a side note you don’t need to close the emulator between run/debug attempts, as it only needs to redeploy the app.

 

If you’re debugging using a device that hasn’t been used for this purpose before, you’ll need to set the device up first. Do this by enabling developer options and within the new menu, switching on ‘Android debugging’ under the ‘Debugging’ header. After this, just plug the device in, accept the dialog on your device confirming this is a safe debugging connection, and you should be able to deploy and run your app with F5. Note physical devices have higher precedence than the emulator and will switch to it as the default debugging option when plugged in.

Once your app has deployed and loaded up, you’ll be greeted by the default single page template. Open the menu in the top right corner to sign in, and once you’ve entered your details you should return to this page with the spinning progress bar before automatically being sent to the dashboard page with your welcome message:

Android login

Learn More About Xamarin, OpenID Connect, and Secure Authentication

If you’ve followed along with all these steps you now have a basic Android app built using Xamarin.Android, with fully functioning user authentication based on OpenID and the Okta service. From here you can easily expand on the dashboard activity to implement your functionality.

To see the code from this post in full head on over to our GitHub page.

If this tutorial has whetted your appetite for Xamarin development and you’d like to learn more, then I’d strongly suggest you have a look at these other great articles:

As always if you have any questions, comments, or concerns about this post feel free to leave a comment below. For other great content from the Okta Dev Team, follow us on Twitter @OktaDev, Facebook, LinkedIn and YouTube!

Your First Android App in Visual Studio

The Android operating system is based on the Dalvik Virtual Machine (VM), which is a mobile-optimised VM similar to the Java VM. Oxygene for Java ships with templates for creating Android projects, and produces both native Java JAR files and the Android APK file necessary for deployment to an Android device.

Because Android runs on such a wide variety of devices with different screen sizes, formats and orientations, it was intentionally designed without a WYSIWYG design surface for building the UI. Instead, an XML file (similar to .NET’s XAML) is edited to lay out the visual elements. There is a free online DroidDraw tool for building Android User Interfaces via a WYSIWYG interface, but editing the XML directly is recommended.

Prerequisites and Emulators

To get started with Android development, you need to install the Java Development Kit and Android SDK, as outlined here (Fire) and here (Visual Studio).

When the tools and platforms are all installed, you will be able to create an Android Emulator, also known as an Android Virtual Device or AVD. You can do this from the Android Virtual Device Manager, which is accessible from the SDK Manager by choosing Tools, Manage AVDs.

Just click New, give the emulator a name and select the API in the Target field. You can choose any installed API level, for example Android 2.2 — API Level 8 (also known as Froyo) or Android 4.0.3 — API Level 15 (also known as Ice Cream Sandwich). Once you’ve specified the SD Card Size for the emulator (say 512) and chosen a skin (a screen resolution) you can use the Create AVD button to finish the job.

Create a new Android Virtual Machine

You can launch the emulator from this screen by selecting it and pressing the Start button.

Android AVD Manager

Note: When you re-run the SDK Manager, it will often find updates to install. As mentioned earlier, if the Android SDK was installed into the default location, it will require administrative privileges to install them. So be sure to run it as Administrator (or install the Android SDK into a custom location to make things simpler).

The first time you create or open an Elements project for Android, it will do a ‘pre-flight check’ to ensure that it can locate the things it needs, notably the JDK and the Android SDK. If you’ve installed them into custom locations and it fails to find them, this gives you an opportunity to specify the installation folders.

Getting Started

In both Visual Studio and Fire, the New Project dialog provides the Android app template under Oxygene for Java and Android.

Visual Studio 2012 - Oxygene for Java - Android - New project

The new Android project is created with a single simple activity called MainActivity . An Activity is the most basic part of an Android app – a single, focused thing that the user can do. The pre-created MainActivity contains a small amount of code to set up a simple UI with a button that, when clicked, displays an incrementing count on its caption.

The visual representation of the screen for MainActivity is defined in the XML file »main.layout-xml» which is in the »res/layout» folder.

Controls are named with the android:id attribute in layout XML. You prefix @+id/ in front of the chosen name and you can then reference the control’s ID in code by prefixing it with R.id. (all IDs become members of the id class, which is nested within the R resource class). To access the control, you can pass the ID into the activity’s findViewById() method. For example, the button named in the layout XML above has an ID accessible in code as R.id.MyButton. To get access to the button object you’d use Button(findViewById(R.id.MyButton)) — notice the typecast to get a Button object, which is needed because findViewById() returns a View object, one of the Button class’s ancestor types.

Strings referenced in the XML attributes with the @string/ prefix or in the code as members of the R.string class are defined in the »strings.android-xml» resource file, which can be found in the »res/values» folder.

To reference the string resource in code from an activity method, you simply call getString(R.string.my_button_text). getString() is a method of the Activity class (or, more accurately, a method of one of Activity’s ancestor classes, Context). As you can see, you pass a string resource ID to the method and it returns the resultant corresponding string.

»’Note»’: In Delphi and in .NET languages we are used to working with properties. A property represents some data with possible side effects when read from and/or when written to. A property Foo is defined in terms of a getFoo() getter function that returns a value and a setFoo() setter function that is passed a value. Java does not support the notion of properties, so classes have many getter and setter methods exposed instead of their equivalent properties. When working with Oxygene for Java, you have the choice of calling the getter/setter type methods that exist in any Java libraries that you reference, such as the Android SDK, or using the property that you might normally expect to exist. So in the case above, you can access a string resource either by calling:

onCreate is the method called when the activity is first created and where your activity initialisation goes. After calling through to the inherited method, you can see that a layout resource ID is assigned to the ContentView property, although given the note above, it should be clear that really we are are passing the resource ID to setContentView(). This sets up the layout file »res.layout-xml» as the UI for this main activity.

Next the code locates the button with the ID MyButton and stores a reference to it in a local variable.

The final job of onCreate() is to set up the button’s click event handler, which is done by assigning an expression to the button’s OnClickListener property, or in truth passing it to the setOnClickListener() method. Because Java uses interfaces to define event signatures, we use Oxygene’s inline interface implementation to associate our ButtonOnClick method with the onClick method of the button’s View.OnClickListener event interface.

The event handler method itself, ButtonOnClick, increments the Count class instance variable and then uses the value to create a formatted string, which is then set as the button’s caption via its Text property (or setText() method). The string formatting uses the value of the my_button_text_2 string resource (shown earlier), which uses Android format string syntax. The formatting method being called is really String.format(). It’s being called as WideString.format() to avoid ambiguity with the String property (getString() method) of the Activity class we looked at just above. WideString is provided by Oxygene as a synonym for the String type.

One really important value in the »strings.android-xml» file is the app_name string. This is used twice by the application:

  • the activity’s title bar has this string written on it and
  • the list of installed apps on the device uses this string to identify the app.

Be sure to update app_name to make it meaningful.

You can find the references to app_name that affect the title bar and the installed app list in the [http://developer.android.com/guide/topics/manifest/manifest-intro.html Android manifest file], »AndroidManifest.android-xml» in the »Properties» folder. Every Android application has a manifest file to let Android know the identity of the application package, the components in the application, any permissions required in order to operate and some other system details.

In this sample application’s manifest you can see the application is given a text label and an icon, and the single activity is identified by its class name and also given a label. The convoluted looking intent filter declaration inside this activity is simply the standard code necessary to tell Android this activity is the main activity of the app.

When you need to add more strings to your project, simply edit the »strings.android-xml» file.

»’Note»’: The various Android resource files that reside within the »res» folder hierarchy are all XML files. They would all be perfectly valid and usable if given the standard .xml extension. The reason for the .layout-xml and .android-xml extensions is to enable the appropriate IntelliSense (or Code Completion) behaviour when working in these files.

Running Your App

When you build your app, the Oxygene compiler first creates a normal Java JAR file and then the Android toolchain creates an Android APK file (Android PacKage). The JAR file is just compiled code (Java byte code) but the APK file is the Java byte code processed to run on Android’s Dalvik Virtual Machine with all the necessary resources packaged into the file. Once the package is built, it is ready to run either on an AVD (in other words on the emulator) or on a physical device.

»’Note»’: To deploy an APK file from your Windows machine to a physical device, such as a phone or tablet, you must first install the manufacturer’s USB driver for the device to allow communication between the PC and the device. Then you connect the device to the PC using an appropriate USB cable. You should be able to locate instructions on how to install the driver on your manufacturer’s web site or by using a search engine.

The Oxygene debugger will automatically deploy the APK to the emulator and launch it when you use the Start Debugging or Start Without Debugging buttons in Visual Studio (or use the F5 or Ctrl+F5 keystrokes, respectively). If you choose Start Debugging (or F5), you can set breakpoints and debug your application from Visual Studio as it runs on the emulator or physical device.

If you have a virtual Android device running and also have a physical Android device connected to the computer, you need some way to tell Oxygene which device to target when you start an application. You can choose an Android device in the Android section of the project properties.

If you want to install the APK manually, you can use the Android Debug Bridge (ADB) command-line tool from a Windows command prompt. The adb.exe tool is located in the »<Android_SDK_installation_path>\android-sdk-windows\platform-tools» folder, where »<Android_SDK_installation_path>» could be »C:\Program Files» or another directory you chose at installation time. It may be of benefit to add both »<Android_SDK_installation_path>\android-sdk-windows\platform-tools» and also »<Android_SDK_installation_path>\android-sdk-windows\tools» to the system search path to enable Android SDK tools to be executed by name no matter what the current directory is.

Simply run adb with the install parameter and the name of the APK to load. If the APK is already installed, you should also specify the -r. Assuming adb’s directory has been added to the search path, you would use:

adb install -r org.me.androidapplication1.apk

»’Note»’: If you have an emulator running and a physical device attached to the PC, you can use the -d and -e switches to specify either the device or the emulator, respectively, for example:

adb -e install -r org.me.androidapplication1.apk

Android Emulator - Deployed

Once the APK is installed, you can run it just like you would any other app.

Android Emulator - Running

UI Elements

The <LinearLayout> tag in »main.layout-xml» is one of several layout options. Some of the other layouts are FrameLayout, TableLayout and RelativeLayout.

    — A frame layout is designed to block out an area on the screen to display a single item. — A layout that arranges its children in a single column (vertical) or a single row (horizontal). The default orientation is horizontal. — A layout where the positions of the children can be described in relation to each other or to the parent. — A layout that arranges its children into rows and columns. A TableLayout consists of a number of TableRow objects, each defining a row. TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.

Once you have the layout, you can add other controls like Button, ImageButton, TextView, ImageView and others.

There is a pretty good UI tutorial available. Keep in mind that the code samples will be in Java instead of Oxygene. However, you should find that the Oxidizer IDE feature can help in porting Java code over to the Oxygene syntax. If you have a snippet of Java code in the clipboard, you can press Alt+Ctrl+V, then J and the Oxidizer will do its utmost to translate the code for you. It won’t necessarily do a perfect job as it’s working without context, but it should do the main bulk of the translation for you.

Oxidizer can port Java snippets to Oxygene

Now for some Toast

When you want to popup a message to your users from an Android app, you make toast. A toast is a small popup window that shows up in front of the current activity for a short time. Simply call the makeText method on the Toast class to create a toast object, then call show() to pop it up on-screen. There are two versions of makeText and each takes 3 parameters. Here is a sample call:

The first parameter is the context that the toast relates to. You can either pass your activity (using self if working in the activity’s method) or a reference to the single application object that exists in the app (accessible via the activity’s getApplicationContext() method), since both Activity and Application inherit from the Context class.

The second parameter is the text string to display. This can either be a literal string as above or, preferably, a string resource ID, depending on which version of makeText you are using. So to pass a resource ID, you would reference a string defined in »strings.android-xml» by using String[R.string.some_identifier].

The last parameter is the duration before the toast is auto-dismissed, either Toast.LENGTH_SHORT or Toast.LENGTH_LONG.

The call to makeText returns a Toast object. There are other methods on the Toast object to configure it. The show method ultimately displays the toast.

Just add the code above to the ButtonOnClick event handler in MainActivity and when you run it in the emulator or on a device, you will see the toast appear when you click the button.

Android Emulator - Running with Toast

A toast never receives focus and always disappears after the duration timeout.

Documentation

For Android documentation, you can make use of the mass of information provided by Google in their API Reference and API Guides. Naturally, this documentation is targeted at Java programmers, but that should really be just a minor inconvenience — the method signatures are laid out in C-style syntax rather than Pascal-style. Oxygene can natively access any of the Android SDK class and call any of the available methods, so the best documentation is the documentation written by the platform provider: Google.

In this primer, various different class types and methods have been linked through to the corresponding Android SDK documentation. You should become familiar with using the Android SDK documentation to learn about how to program Android applications in Oxygene for Java.

Notes

One important thing to remember for Android as you start building larger projects and making use of additional libraries is that if you don’t set the “Copy Local” property to true for a referenced library, the compiler presumes the library is available on the system and does not include it in the generated archive. If you set it, it becomes part of the application. For the main platform library, such as android-14, “Copy Local” must be left as false, but for all other libraries it must be set to true to ensure the referenced code will be available when the app runs on an Android device.

Как создать приложение на андроид в visual studio

Для создания кроссплатформенных приложений для Xamarin Forms в Visual Studio 2019 предназначен шаблон проекта, который называется Mobile App (Xamarin.Forms) . Для быстрого поиска шаблона проекта можно отфильтровать шаблоны по ключу «xamarin»

Типы проектов для Xamarin Forms в Visual Studio 2019

То есть для создания проекта приложения нам по сути надо выбрать первый тип проекта.

Итак, создадим первый проект. Для него выберем тип Mobile App (Xamarin.Forms) и назовем его, к примеру, HelloApp :

Создание проекта Xamarin Forms в Visual Studio 2019

После этого будет предложено выбрать шаблон проекта и установить ряд настроек:

Шаблоны проектов для Xamarin Forms в Visual Studio 2019

Здесь нам доступно три шаблона:

Floyout : проект с боковым меню

Tabbed : проект приложения, которое использует вкладки для навигации между страницами

Blank : пустой шаблон, создающий проект с минимальной функциональностью

Кроме того, при создании проекта в опции Platform мы можем отметить, под какие ОС будет создаваться проект. В данном случае мы можем выбрать все платформы: Android, iOS, Windows (UWP).

Windows (UWP) доступна только под Windows, если для Visual Studio установлен инстументарий для разработки под UWP.

В данном случае в качестве шаблона проекта выберем Blank .

И Visual Studio сгенерирует новое решение. Если мы выбрали выше все три платформы, то созданное решение будет содержать четыре проекта:

HelloApp : главный проект библиотеки, которая и будет содержать всю основную логику приложения

HelloApp.Android : проект для Android

HelloApp.iOS : проект для iOS

HelloApp.UWP : проект для Windows 10

Однако в зависимости от операционной системы набор проектов может быть иным. Например, при работа в Visual Studio для Mac в MacOS будут достуны только три проекта: общий проект библиотеки, проект для iOS и проект для Android.

Главным будет самый верхний проект (в данном случае HelloApp ). Он будет содержать весь код и определение интерфейса, которую затем будут использовать все остальные проекты.

Если мы обратимся к главному проекту, то в нем уже будет четыре основных файла:

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *