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 didnt 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 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 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, Ill 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.
Note: This Version Of The Codelab Requires Android Studio 36 Or Higher
You can download Android Studio 3.6 from the Android Studio page.
Android Studio provides a complete IDE, including an advanced code editor and app templates. It also contains tools for development, debugging, testing, and performance that make it faster and easier to develop apps. You can use Android Studio to test your apps with a large range of preconfigured emulators, or on your own mobile device. You can also build production apps and publish apps on the Google Play store.
Note: Android Studio is continually being improved. For the latest information on system requirements and installation instructions, see the .
Android Studio is available for computers running Windows or Linux, and for Macs running macOS. The OpenJDK is bundled with Android Studio.
The installation is similar for all platforms. Any differences are noted below.
Deploying And Launching The Application
After the emulator starts up, slide the lock button to the right to show the Android home screen:
Back in the Select Device dialog, we can now build and deploy our app by selecting the emulator in the list, and then clicking OK. The first time a Xamarin.Android application is installed, the Xamarin.Android shared runtime will be installed, followed by the application.
Xamarin.Android deploys the app to the emulator, and then launches it. The default app created from the template consists of a Button. Clicking the button increments a counter, as shown below:
Read Also: Remote Control My Pc From Android
Find Bugs On Any Device Before Release
Does your app still work after your latest change? How does it perform on an LG G2? Find out by testing your app in a hosted device lab with 1000s of real iOS and Android devices. Youll receive test results, full-resolution screenshots of every step, along with performance metrics.
Test every step of every feature. On every device. On every commit. Welcome to the future of app testing.
Creating A Xamarinandroid Application
Lets begin by creating a new Xamarin.Android solution. Xamarin.Android includes several templates for creating projects, including:
- Android Library Project A reusable .NET library project for Android.
- Android Application A basic starter project with a single activity.
- Android OpenGL Application An OpenGL starter project.
Were going to use the Android Application template for this walkthrough. Lets create an application by doing the following:
Read Also: Quick Cash Apps For Android
Can I Develop App In Visual Studio
The process of developing an Android app can be done with Visual Studio. The IDE has a built-in debugger and allows the developer to view the applications code while running on an emulator. The debugger is also included in Visual Studio, and can be accessed via the Start Debugging and Start Without Debugging buttons. Visual Studio also includes the Google Android Emulator. Xamarin Live is an app that runs on an Android phone and hooks into Visual Studio resources. This gives you real-time previewing and debugging of your Visual Studio-developed app on an Android phone.
There are pros and cons to both tools. While Visual Studio is more popular among developers, it is not the only one. NetBeans and IntelliJ IDEA both have Android plug-ins, while Visual Studio does not have native Java support. While Visual Studio is easier to set up, it may not be the best choice for developers. It may not be the best choice for every project, but it can be a good option if you want to develop Android apps.
Fix Errors If Necessary
If you edited the XML for the layout directly, you might see some errors.
The errors occur because the buttons have changed their id and now these constraints are referencing non-existent views.
If you have these errors, fix them by updating the id of the buttons in the constraints that are underlined in red.
Read Also: Best App To Fax From Android
Set Up The Repository
Go to the Build service in App Center.
Choose GitHub as the selected service.
Sign in to GitHub, and click .
Choose the main branch.
Click Configure build. The Build configuration panel will show up.
The default setting for build frequency is Build this branch on every push. Every time you push code to a configured branch, a build will automatically begin. You can enable this continuous integration feature or opt to manually choose when builds run.
If you want to run the build on a device, turn Sign builds on. If you followed the instructions on Getting Started, you can upload your keystore file and fill in the environment variables or check My Gradle settings are entirely set to handle signing automatically.
Click Save at the bottom of the page, and the build will begin.
The build should complete after a couple minutes. Once the build has completed, you can download the results by clicking . This includes logs and, if the build was successful, build output and symbols.
Using The Library On Android
Changes needed on an Android app are very similar to those needed on iOS. Modify the MainActivity.cs file to match the following:
using Android.App using Android.Widget using Android.OS namespace testshared.Droid } public void doneCallback ) } }}
Note:The system architecture of both platforms, Android and iOS, requires that all UI interaction happen on the main application thread. This means that any change to UI elements should happen from within the main thread as well. That is where RunOnUiThread and InvokeOnMainThread come in. Since HTTP requests were executed in a separate thread and doneCallback was called outside the main thread, we had to use these methods to be able to access the buttons and change the label.
You May Like: How To Mine Cryptocurrency With Android
One Technology Stack To Code For All Platforms
Xamarin uses C# complemented with .Net framework to create apps for any mobile platform. Thus, you can share an average of 80-90 percent of the code across platforms speeding up the engineering cycle. Xamarin also does not require switching between the development environments: You can build all of your Xamarin apps in Visual Studio or Visual Studio Code. The cross-platform development tools are provided as a built-in part of the IDE at no additional cost.
Building The App For Release
You have two possible release formats when publishing tothe Play Store.
- App bundle
Warning: Recently, the Flutter team has received several reports from developers indicating they are experiencing app crashes on certain devices on Android 6.0. If you are targeting Android 6.0, use the following steps:
If you build an App BundleEdit android/gradle.properties and add the flag:android.bundle.enableUncompressedNativeLibs=false.
If you build an APKMake sure android/app/src/AndroidManifest.xmldoesnt set android:extractNativeLibs=falsein the < application> tag.
For more information, see the public issue.
Read Also: Remote Control Android Phone Over Wifi
Send The Count To The Second Fragment
The Next/Random button was set up by Android Studio to go from the first fragment to the second, but it doesn’t send any information. In this step you’ll change it to send a number for the current count. You will get the current count from the text view that displays it, and pass that to the second fragment.
int currentCount = Integer.parseInt.toString)
FirstFragmentDirections.ActionFirstFragmentToSecondFragment action = FirstFragmentDirections.actionFirstFragmentToSecondFragment
Xamarinforms Will Soon Cease To Exist
In May 2020, the annual Microsoft Build conference was held. Among other news, it was announced that Xamarin.Forms is going to merge with .NET and evolve into a new cross-platform framework called .NET Multi-platform App UI, or MAUI. MAUI is going to have all native UI and provide access to all native APIs.
Also, as part of the gradual .NET unification, Xamarin.Android and Xamarin.iOS will eventually become part of .NET 6 as .NET for iOS and .NET for Android and will be updated to match other .NET workloads. The timeline for that is unknown yet, so stay tuned for future updates.
Meanwhile, the Xamarin.Forms migration should take place in November 2021. Once MAUI is released, Xamarin will be supported for another 12 months. So, if at the moment you are working with Xamarin or if you plan to build new Xamarin apps, its worth keeping an eye on the dates and looking for Microsoft guides for a smooth transition.
Also Check: How To Lock Down My Child’s Android Phone
Get Your Ui Ready For The Next Task
The next task is to make the buttons do something when they are pressed. First, you need to get the UI ready.
The buttons should now have the following text and ids:
Build An Opengles Application On Android And Ios
The OpenGL ES Application project template under Visual C++-> Cross Platform node is a good starting point for a mobile app targeting both Android and iOS. OpenGL ES is a 2D and 3D graphics API that is supported on many mobile devices. This template creates a simple iOS app and an Android Native Activity app which has C++ code in common that uses OpenGL ES to display the same animated rotating cube on each platform.
The created OpenGL ES Application solution includes three library projects in the Libraries folder, one for each platform and the other one for shared C++ code, and two application projects for Android and iOS respectively.
Now lets run this app on both Android and iOS.
Recommended Reading: Android Developer Salary Entry Level
How To Import An Existing Project In Android Studio
In order to start configuring, you need to install the Android studio and the Java SE Development Kit. First download the android studio from here: Android Studio.
To import the template, simply open Android Studio and import/open the template. Make sure to wait for all the processes to complete before continuing to the next step.
Sometimes, the Gradle Build fails. In some cases, additional components are needed and Android Studio will ask you to do download these additional SDK components. In the messages tab, simply follow the instructions provided to install and download the additional components.
Compiling Our App On Android
Before compiling our app on Android, I have some bad news for Windows users. Youll need Linux or macOS to compile your Android application. However, you dont need to have a separate Linux distribution, instead, you can use a virtual machine.
To compile and generate a full Android .apk application, well use a tool called Buildozer. Lets install Buildozer through our terminal using one of the commands below:
pip3 install buildozer//pip install buildozer
Now, well install some of Buildozers required dependencies. I am on Linux Ergo, so Ill use Linux-specific commands. You should execute these commands one by one:
sudo apt updatesudo apt install -y git zip unzip openjdk-13-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-devpip3 install --upgrade Cython==0.29.19 virtualenv # add the following line at the end of your ~/.bashrc fileexport PATH=$PATH:~/.local/bin/
After executing the specific commands, run buildozer init. You should see an output similar to the screenshot below:
Buildozer successful initialization
The command above creates a Buildozer .spec file, which you can use to make specifications to your app, including the name of the app, the icon, etc. The .spec file should look like the code block below:
After the process is done, your terminal should have some logs, one confirming that the build was successful:
Android successful build
Android .apk in the bin directory
Also Check: Io Branch Sdk Android Library
Download Visual Studio Extensions
After the workspaces have downloaded, Visual Studio should have started. If not, press the windows button + s and search for Visual Studio and run it.
Select the Continue without code option underneath “Create a new project”. A new window should load with a tool bar spanning the top of the windows. Follow these steps to install the needed extensions:
Understanding App And Shell
The last thing I want to talk about is what is in our *App and what is in our Shell:
Inside of our App.xaml you will find global resources such as Primary that we used earlier on the button, but also styles such as a global Button style that we are using with states when enabled and disabled. If you open up the App.xaml.cs code behind you will the creationg of the App that is setting the MainPage to our AppShell and also has additional events similar to our page, but for the app such as when it started, went to sleep , and resumed.
The AppShell.xaml houses the Shell of our application structure. It includes styles and colors for our app shell, and then has additional items for tabs, flyouts, and pages that are displayed. Here we will find two FlyoutItem elements that represent the AboutPage and the BrowsePage. Additionally, it has a MenuItem to display a login/logout button. The ShellContent has a binding to our page that we created and automatically the pages will appear and navigate to each of them when selected.
There is a lot more to Xamarin.Forms Shell and creating apps with Xamarin, but hopefully this puts you on the starting path to getting going with your app. Be sure to follow the .NET dev.to account for more entries in this series.
Recommended Reading: How To Put A Sim Card In An Android
Need Advice About Which Tool To Chooseask The Stackshare Community
Android Studio vs Visual Studio: What are the differences?
Android Studio:Android development environment based on IntelliJ IDEA. Android Studio is a new Android development environment based on IntelliJ IDEA. It provides new features and improvements over Eclipse ADT and will be the official Android IDE once it’s ready Visual Studio:State-of-the-art tools and services that you can use to create great apps for devices, the cloud, and everything in between. Visual Studio is a suite of component-based software development tools and other technologies for building powerful, high-performance applications.
Android Studio and Visual Studio can be primarily classified as “Integrated Development Environment” tools.
“Android studio is a great tool, getting better and bet “ is the primary reason why developers consider Android Studio over the competitors, whereas “Intellisense, ui” was stated as the key factor in picking Visual Studio.
According to the StackShare community, Visual Studio has a broader approval, being mentioned in 676 company stacks & 1009 developers stacks compared to Android Studio, which is listed in 928 company stacks and 690 developer stacks.
GIve a minute to see what Flutter + Dart could offer to you. Dart is modern null safe typed language, has lots of similarities to known languages, so it’s pretty simple to learn. Flutter offers way to create multi platform UI’s using composition. And result is performant on mobile devices.
Create A Blank App Project
First you will need to close out of Visual Studio, then reopen it so you are sent back to the home menu. Now select the option called Create a new project under “Get started”. It will ask you for what kind of application you would like to create. Under the All platforms tab select Android, and under the All project types tab select Mobile. Select the Basic Application option and press the next button. You should be sent to a page instructing you to enter a project name, name it FlashlightApp. Also make sure that Place solution and project in the same directory is selected. Press the create button when done.
Recommended Reading: A Calendar App For Android
Getting Started With Kivy
First, youll need a new directory for your app. Make sure you have Python installed on your machine and open a new Python file. Youll need to install the Kivy module from your terminal using either of the commands below. To avoid any package conflicts, be sure youre installing Kivy in a virtual environment:
pip install kivy //pip3 install kivy
Once you have installed Kivy, you should see a success message from your terminal that looks like the screenshots below:
Successful Kivy installation
Next, navigate into your project folder. In the main.py file, well need to import the Kivy module and specify which version we want. You can use Kivy v2.0.0, but if you have a smartphone that is older than Android 8.0, I recommend using Kivy v1.9.0. You can mess around with the different versions during the build to see the differences in features and performance.
Add the version number right after the import kivy line as follows:
Now, well create a class that will basically define our app Ill name mine RandomNumber. This class will inherit the app class from Kivy. Therefore, you need to import the app by adding from kivy.app import App:
In the RandomNumber class, youll need to add a function called build, which takes a self parameter. To actually return the UI, well use the build function. For now, I have it returned as a simple label. To do so, youll need to import Label using the line from kivy.uix.label import Label: