?

Log in

No account? Create an account

September 5th, 2017

This is the Lesson 1/Lab 1 of the Xamarin Tutorial


Now let’s start with Xamarin Mobile Development.



What is Xamarin?


Xamarin is a mobile development platform which uses C# to create mobile application for Android, IOS and so on.


In Xamarin we use C# as a single language to write and create mobile applications for all major platforms.


Hence Unlike other Solutions which use interpretation, Xamarin is natively compiled on the machine which makes it a preferable option for building high-performance apps with native look and feel of their respective platform.


In Xamarin, while the code related to database access, business logic and network communication can be shared across multiple platforms, The Xamarin Development allows you to create platform-specific UI code layer.


So Xamarin cross-platform applications look 100% native on any mobile device.


Thus providing better user experience and feel as compared to other hybrid apps.


Do watch the following video of Xamarin Mobile Development :-



Prerequisites for Xamarin Mobile Development:


  • Visual Studio 15 with update 3 or Visual studio 17 (either Xamarin Studio Add-on Installed )

  • With Xamarin studio also Ensure that you have installed Android Development SDK in Visual Studio 15


  • In Visual Studio 17 just check Mobile Development with .Net and Install



In this Tutorial we will be opting for Android App development in Xamarin on a Windows Machine.


Development of IOS apps on Visual Studio requires MacOS.


The recommended Operating system for Xamarin Development is Windows 10 with at least 4gb of ram and a dual core cpu.


But the minimum operating system version is Windows 7.


Also Xamarin. Forms Windows support requires Windows 8.1, and Xamarin. Forms UWP support requires Windows 10.


Let’s get started with Xamarin Android Development...


When you open a new project in visual studio and if you see the following options under Visual C# namely Android, iOS and Cross-Platform it means Xamarin has been properly installed on your system.



Xamarin has two approaches for Mobile app development:


  • Xamarin Native

  • Xamarin Forms



We must choose one of these approaches before we can continue further.


Xamarin Forms (Cross-Platform):


  • We can create a single UI for all platforms.

  • Fast Cross platform development.

  • Used in apps where UI is less important than code sharing and we have a single code base.

  • More suitable for simple application with a few functionality which do not require platform specific code functionality.


Xamarin Native (Android, iOS):


  • We can create one UI per respective platform.

  • We can customize and get the maximum out of our UI.

  • The cross platform development in this approach is slow.

  • We have multiple code bases.

  • This apps exploit the most out of the native OS and use many platform specific API’s

  • This are well polished apps which serve multiple functionality and work with smooth interface and fast operations.


Now let us start with Xamarin Native Programming with android...


Click on the Blank Android option and create a new android application.





We use Emulators in Xamarin to test Android Applications


Emulators are software applications which simulate mobile environments like android, iOS and other in out Computer.



We can download different emulators in the options for emulator and the latest version supports all previous versions of android apps built.


The android emulator works inside a virtual machine so deployment time may depend upon your system configuration.


When we press the green emulator button Visual studio will launch the emulator and our application icon along with its name will appear in the simulated android phone.


Copy right www.questpond.com

Activity can be defined as any action performed by the user concerning our app.

User interacts with our application to do different tasks such as viewing photos, videos, music etc.

This activities can be categorized into two types:


  • Assets
  • Resources


Assets files are fixed such as logo or images which need to be loaded without any alteration

So Assets are files without options or raw without alternatives.

Resources are files which can be loaded according to environment.



In resources there is folder called drawable.

According to your version of Xamarin this may or may not contain an image file called Icon.png.

This is your default image that is displayed on your emulator.

Now let’s create another folder called drawable-hdpi, what this does is tell the Xamarin to use the image under drawable-hdpi if your phone has a high pixel density or has a high resolution.

In the ResourcesDesigner.cs file all entries in the resources folder generate a unique id.

This id’s are used to recognize and load resources into the user interface.





As we can see a new ID has been generated for icon.png file.

But it is recommended that you store your app icons in minmap folders which have different resolution named folders ready to use.




Now let’s start building a simple application

Go to Layout folder in Resources and click on Main.axml

This will launch a designer window




Now in toolbox which can be found on the left-hand side of visual studio or just open View in the upper menu to see it.

Follow the procedure as shown:




Drag and drop Plain Text, Button and Large Text in the order shown above.

Now rebuilt to generate Id’s in ResourceDesigner


When we launch our application the first thing to run is the MainActivity.cs file



As we can see MainLauncher is set to true this is what launches the MainActivity.

Now uncomment the code line in the MainActivity.cs which is
SetContentView(Resource.Layout.Main);

The above line allows us to load the startup User Interface.





When the user starts an Activity or clicks on the app the MainActivity.cs is invoked which in turn invokes ResourcesDesigner.cs which loads Icon, UI and Buttons etc. in the application.


Great we are done with the UI designing let’s get to coding.


Double click on the button in Main.axml or just go to MainActivity.cs .


Declare three variables as null for EditText, Button and TextView as show below:




Next Write




In the above image FindViewById is used to locate the button resource id generated in ResourcesDesigner.cs and typecast it as generics to "btn" along with editxt and txtview.

The Next line of code say when someone click on the button append Hello to the text entered in the editxt (Plain Text) also the + sign represents event to be subscribed.




Now deploy the application



Here is a startup video tutorial on Xamarin :-

Copy right www.questpond.com

Here is a very simple overview of Android Activity with sequence of states


Initially we start our application now there may be some interruption like a phone call we might need to attend so the application gets interrupted and runs in the background.

After we are finished with the phone call the application gets restarted and comes to the foreground so that we can resume our activity.

After completing our activity we can choose to exit it with the back button.

Here is a more detailed Android Activity Lifecycle which explains the applications working from start to exit.




There are seven events in the above diagram some of them will help us track the transition and some will help to track the state.

OnCreate event is an event which starts only once at the launch of the application.

OnStart event occurs after OnCreate and all the user interface is loaded but the application is still not visible.

OnResume causes the application to become and hence the app starts running in the foreground of your android device.

OnPause event occurs when any kind of interrupt occurs which causes the application to go into the background by various reasons such as incoming calls etc.


OnStop event is called when the app goes to the background or a visible false state.


OnRestart occurs when the interruption that caused OnPause event is finished and since the app is running in the background app can resume its functionality while calling the OnResume event. But it is still not visible as it can only come to the foreground in OnResume.


OnDestroy is the event where the user exits the application or it is terminated by the device due to low device memory.

To this Events in Action let’s write the following code in your MainActivity.cs .



Add a Multiline text in the designer window

Rebuilt to generate Resource Id and add the above code in your project.

Next add the following code to see the occurrence of events in your application


Also add the custom text below each event to see it in the MultiText window.

Now let’s rebuild and start the app


As we can see OnCreate, OnStart and OnResume event get triggered.


Let’s go to the appdrawer in the Android emulator and return to the app.



As you we can see OnPause, OnStop we executed and as we returned to the application OnRestart, OnStart and OnResume were started.

See the below video to understand basic concept on Xamarin Mobile Development :-

Copy right www.questpond.com

Below is a youtube video which demonstrate about Xamarine Mobile Development concept :-



Dialog boxes are message boxes that are used by the developer to convey a particular message regarding the functionality of the application to the user.

So that the user can click on the buttons on the dialog boxes to perform a particular action.

These are steps involved in making a Dialog Box:


Step 1: we have to create an object of type builder which is used to create dialog box.

Step 2: Now create a dialog box object.

Step 3: Next Create a button, TextView and Title for dialog boxes as shown below:



In the above code we have created an anonymous function to create three button in dialog box on pressing each will display an output in the TextView.

The title is defined in SetTitle while message text in SetMessage.

Intent

Intent are messages which are passed through activities to services as they define what we want to do.

Now to use Intent we need to create an object of intent and the following code:



The string inside the Parse function is a telephone number.

The above code we created an uri object using Uri.Parse and we pass the uri to Intent.


ActionDial is used to pass the Intent that we want to dial a number and StartActivity is used in which we pass dialingintent.

But we might encounter some error in the above code if we want we can remove Android.Net add the following in the namespaces




Now deploy the app and click on the button.

We will see the following action on the device which is the Dialer called and the Telephone no in the string is passed to the dialer.



In the same way we can write the application code such that we can view a geolocation in our device.

With the following code:




Let’s alter this code to Visit a particular site




Copy right www.questpond.com

Multiforms in Xamarin means to have multiple views instead of a single view like Main.axml and our application can navigate between those and pass data in between them.

Okay now let’s get started by adding another form in our application.



Next we a new activity to invoke the SecondForm as every UI in android is invoked via activity.



Add the following code to ActivitySecondForm to enable it to invoke SecondForm.



We need to send a call from Main form to SecondForm



Now from our Main activity we need to invoke the ActivitySecondForm so let’s do it by adding this code to MainActivity.

For this we need to create an object of Intent and as we learned earlier StartActivity is used to start any activity.



As you can see below we can now navigate from one form to another form.



Now we need to pass the data from one page to another



Let’s create an object of Person so that we can pass data from one page to another but we need to pass it in json format.

So we need to serialize the object of Person.





Now pass parameters into the object created



But for using Json we need to install some dependencies so let’s use Visual Studios Inbuilt package manager which is Nuget.

In Nuget Package Manager go to browse and install Newtonsoft.Json.



After installing you should see Newtonsoft in your references.



To convert the object to json use the following code:



Here the persondata is the key and jsonperson is value which is passed in the PutExtra method.



PutExtra is used to push the data with the key while GetStringExtra is used to receive data while providing the key.

After passing data from MainActivity.cs to ActivitySecondForm.cs .we need to deserialize it to a normal format to display it in the small TextView which we need to create in ActivitySecondForm before we write this code



Code to be written in ActivitySecondForm.cs



Important note don’t forget to add Newtonsoft.Json in the name space above.

Good we are done with the coding part so just deploy the application next to see the Output:



Our data which was name and address have been passed from the Main form to the Second form.

Before starting with the labs do watch below Xamarin stratup video
:-

Copy right www.questpond.com

As greats as it using an Android emulator it’s a pain to debug applications in it.Emulators are slow and laggy plus they can never compare to a real android device experience as they do not support some of the functionalities of a real device.

The reasons to debug on real device:

  • To check accelerometer and physical motions.

  • Emulator debugging is slow and configuration is complex.</br>
    To test your application on your Android device follow the steps shown below:

  • Turn on USB debugging in your android settings by going into about device and then click on the built number multiple times and then go to the outer settings menu to turn it on.



Now connect your phone to your pc via USB take care that USB debugging is still switched on.




As you can see we have our device show up in the emulators list.

Now run the app in the phone by pressing the green emulator icon.



As we can see our device has hosted our application and so it’s a real test on device rather than an emulator.

You can also go thorugh below simple video of Xamarin Mobile Development :-

Copy right www.questpond.com

Services are applications which run in the background to perform a particular function.

Example :- Tracking geolocation

In order to create a service we have to create from the service class.





Services are important part of Android applications as they are used by application to access various features of the android devices native platform.

Now let’s create another class called BackGround class so that we do not mix up our code.



Now create a class called some SomeBackGroundTask that inherits from the Service class.



Next we need to override some methods in the class first being the OnBind method, second being OnStartCommand (It is used to invoke the background logic) and the third one which is StopService (It will fire before our service stops).

Create a Method named RuninBackGround() and call it in OnStartCommand and define how we can restart our service using enum inbuilt in OnStartCommand.






The above diagram describes different ways in which a service can be restarted.

Sticky :- If our service is stopped it will be restarted automatically but the last intent will be forgotten and intent passed will be none.

Not-Sticky :- It means the service must be started manually will not start automatically.

Redeliver Intent :- The service will restart automatically and it will try to deliver the intent before the service has failed.

Sticky Compatibility :- It will try to restart the service depending whether you are below android API 5 or above. For API below 5 you must start the service manually

Here is the code for SomeBackGroundTask class




Also do not forget to add the namespaces





System.Threading is used in the Timer Function.

We are using _timer to invoke the message in the debug window every four second.

In the StopService we also log message in Debug Log window.

In MainActivity.cs we would like to invoke SomeBackGroundTask.




Be sure to reference BackGroundTask namespace.

In StartServive we say start a service with an Intent to start BackGroundTask

Now running our application in Debug Mode




Explicit and Implicit Intent:



Explicit Intent is needed when we are working with a service.

Implicit Service Example :-




This is the Implicit service were we actually pass the class name.

Explicit Intent :-

In this Intent we decouple our client from our Service.

To use Explicit Intent we use




IntentFilter ask under which circumstance should it invoke the service so we pass a metadata and call the service from MainActivity hence we don’t have refer the strongly type class name and just pass i in the StartServive and meta data in the Intent as shown below:





Output:




AND

Do not miss to watch our Xamarin video tutorial below :-

Copy right www.questpond.com

Tags

Latest Month

September 2017
S M T W T F S
     12
3456789
10111213141516
17181920212223
24252627282930
Powered by LiveJournal.com