Getting Started With Xamarin Android Single View App

Introduction

In this article we will see in detail how to create our Xamarin Android Single View App. You can develop the Xamarin application as Xamarin.Forms for Cross Platform or you can develop native app for Android and IOS using Xamarin.iOS and Xamarin.Android. In this article we will see how to create a native app for Android and here we have selected the Xamarin Android for Single View App.

In this Mobile App we will see how to:

  • Display the Current time using TextClock
  • Create a Notification to display the click Counts
  • Add a Music (MP3) file to resource
  • Play Song with added MP3 file
  • Stop the Song
  • Increase the Mobile Volume
  • Decrease the Mobile Volume

In this Mobile App we will be adding TextClock to display the current time and five buttons. In the first button click event we will be displaying the notification at the top with count of button click. In second button click event we will play song using the added mp3 from resource. In the third button click we will stop playing the song. In the fourth button click we can increase the volume of the playing song. In the fifth button click we can decrease the volume of sounds.

Prerequisites

Make sure you have installed all the prerequisites in your computer. If not, then download and install all, one by one.

  1. First, download and install Visual Studio 2017 from this link

Make sure you have installed the Mobile development with .NET

 

Xamarin

 

Using the code

Step 1 - Create your Xamarin  

After installing our Visual Studio 2017 click Start, then Programs and select Visual Studio 2017 - Click Visual Studio 2017. Click New, then Project, select Visual C# and Android then select Single-View App (Android). Enter your project name and click 

Xamarin

Step 2

Xamarin Android Project Structure

Xamarin

References

The References has the default .Net assemblies like System,System.core and for Xamarin Android the most important reference is the Mono.Android ,by default this reference will be added as we can see in the image. This Mono.Android reference will be used to interact with our C# code and Android API’s.

MainActivity

Xamarin

In our .Net applications by default the Main method will be run and from our application it will start execution but in Android app we have collection of activities and each activity will be used for a single view and when we create the Xamarin Android application the MainActivity.cs is created by default. Here we will be using this activity to run our app. All the activities will be inheriting from the Activity class as when we open the MainActivity.cs file we can see that. From our MainActivity we can set the view which needs to be displayed when we run our App. Here we can see by default  the Main View has been added to SetContentView.

How to set the default Main Activity when we have multiple Activity?

As we told you that in our Xamarin.Android App we can have multiple activities and need to have one main Activity to show by default when we run the App. If we have more than one activity  then we can set the top of activity code as “MainLauncher = true” for that activity and false for other activities.

You can also set the Label (Title) for your app from the Activity, here we have set the title as “Shanu Music App” and also we can set Icon for the App.

Xamarin

Lifecycle of Activity

  • OnCreate() -> When the Activity is created
  • OnStart() - > When the Activity is started
  • OnResume() -> Called when Activity will start interacting with user.
  • OnPause() -> Activity is not visible to user(Working in Background)
  • OnStop() -> Activity is not available for user
  • OnDestroy() -> Before the Activity is destroyed

In our demo we have by default the OnCreate() and we will be using this to show our view when the App is running with button click events to perform our needed actions.

View

Activity and Views are the important part of Xamarin Android Apps. As we see the Activity is used to show our View and to write code for the events and View is used to design our App.

Xamarin

Views will be located inside the Resources and Layout Folder. We can see by default Main.axml will be added in our layout folder. The view will be as a “axml” file and it's purely of XML code.

Xamarin

When we open the Main.axml file we can see the Designer and Source part. We can add controls as drag and drop from Toolbox as per our need and design our Android App. When we click on the Source part we can see the controls are added to our App in XML code like below.

Xamarin

Values / Strings.XML

We can see that in our Button text the caption is added as “android:text="@string/hello” and here the “="@string/hello” means that the text will be loaded from the Strings.XML

Xamarin

The string for the hello will be added in the Strings.XMl from the Resources \ Values\

We can change or add the string as per our needs.

Xamarin

Resource.Designer

All the resources like controls we are adding in the View, or the text we are adding in the String.XMl file, will be generated with a unique number in the Resource.Designer file from the solution. 

Xamarin

I hope you have some basic understanding on working with Xamarin Android App and now let’s focus on how to add more controls to make our simple Music App.

Step 2 - Working with Code

Displaying Time using TextClock

We will add the TextClock control to our App and design with the below code, here we have set the format as 12 hours and set the font size and color.

  1. <TextClock xmlns:p2="http://xamarin.com/mono/android/designer-default"  
  2.         android:format12Hour="hh:mm:ss a"  
  3.         android:layout_width="match_parent"  
  4.         android:layout_height="47.5dp"  
  5.         android:id="@+id/textClock1"  
  6.         android:gravity="center_horizontal"  
  7.         android:textColor="#ffccff"  
  8.         android:textSize="40sp"  
  9.         android:layout_marginBottom="4.5dp" />  

When we run the application, we can see the output in the emulator as the time which will be displayed in our application and the time will be automatically displayed with the current time and second.

Xamarin

Displaying Notification

Now we will add a button and in the button click event we will display the notification at the top with the number of times the user clicked on the buttons.

  1. <Button  
  2.      android:id="@+id/myButton"  
  3.      android:layout_width="match_parent"  
  4.      android:layout_height="wrap_content"  
  5.      android:text="@string/hello"  
  6.     android:background="@android:drawable/alert_dark_frame" />  

We need to add the Xamarin.Android.Support v4  package to our APP. Right click on the solution and click on Manage NUGet Package and search for Xamarin.Android.Support.v4 and click on install.

Xamarin

We can see the new Xamarin Android Support dll has been added to our project.

Xamarin

In the MainActivity.cs file now we will create the button click event for the above design. First we import the below reference to our MainActivity.cs file

  1. using Android.Support.V4.App;  
  2. using Android.Support.V4.View;  
  3. using Java.Interop;  
  4. using Android.Views.Animations;  

In the MainActivity .cs onCreate method we will create the button click event to display the notification message in our Mobile device. For this we create object for the NotificationCompact and we set the Title and Text for our Notification message and in the Text we also set the counter value to display how many times the button has been clicked from our notification.

  1. Button btn = FindViewById<Button>(Resource.Id.myButton);  
  2.             btn.Click += delegate {  
  3.                 var notification = new NotificationCompat.Builder(this)  
  4.                             .SetContentTitle("Shanu - Notifications")  
  5.                             .SetContentText("Clicked " + count++ + " times!")  
  6.                         .SetSmallIcon(Android.Resource.Drawable.DialogFrame)  
  7.                             .SetGroup("testGroup").Build();  
  8.   
  9.                 var manager = NotificationManagerCompat.From(this);  
  10.                 manager.Notify(1, notification);  
  11.                 btn.Text = "Check Notification!";  

The code will look like this.

Xamarin

Notification Output

When we run the application, we can see the output in the emulator with the Button.

Xamarin

When we click on the Button we can see the Notification at the top with the count value display showing how many time the user clicks on the button.

Xamarin

Playing the Song

First, we add our favorite MP3 songs to our Resource folder and for this simple demo, we have added one mp3 file to be played.

Create the raw Folder

Xamarin

We need to create a folder inside our Resource folder named raw and we will be adding all our mp3 files to this folder. To add the mp3 file right click on the raw folder and Add Existing Item and select your mp3 file which needs to be played. Here we have added one mp3 file to our raw resource folder.

Xamarin

Next create an object for the MediaPlayer

  1. MediaPlayer mp;  

For adding the MediaPlayer we import the reference as below to our MainActivit.cs file

  1. using Android.Media;  

Now we will add a button and, in the button click event we will play the music from our newly added mp3 resource file.

In our Main.axml file design your button

  1. <Button  
  2.         android:text="Play Song"  
  3.         android:layout_width="match_parent"  
  4.         android:layout_height="wrap_content"  
  5.         android:id="@+id/button1"  
  6.         android:background="@android:drawable/alert_dark_frame" />  

Add the button click event for Play Song button from our MainActivity.cs and add the below code to play your music.

  1. // to Play the Song  
  2.         Button btn1 = FindViewById<Button>(Resource.Id.button1);  
  3.         btn1.Click += delegate  
  4.         {  
  5.             mp = MediaPlayer.Create(this, Resource.Raw.Kannalanae);  
  6.             mp.Start();  
  7.   
  8.             btn1.Text = "Song is Playing Now enjoy :)";   
  9.         };  

Play Song Output

When we run the application, we can see the output from our emulator and we can see the newly added Play Song button in our App.

Xamarin

When the user clicks on the Play Song button they can listen to the songs which they have added.

Xamarin

Stop the Song

For stopping the playing song, we will create a new button and, in the button click event we will write our code to stop the playing song.

Now we will add a button and, in the button click event we will stop the playing music.

In our Main.axml file design your button to stop the music

  1. <Button  
  2.         android:text="Stop Song"  
  3.         android:layout_width="match_parent"  
  4.         android:layout_height="wrap_content"  
  5.         android:id="@+id/button2"  
  6.         android:background="@android:drawable/alert_dark_frame" />  

Add the button click event for stop the playing song from our MainActivity.cs and add the below code to stop the playing music.  

  1. // to Stop Playing  Song  
  2.         Button btn2 = FindViewById<Button>(Resource.Id.button2);  
  3.         btn2.Click += delegate  
  4.         {  
  5.             if (mp != null)  
  6.                 if (mp.IsPlaying)  
  7.             {  
  8.                 mp.Stop();  
  9.                 btn2.Text = "Song Playing Stopped :( ";  
  10.             }  
  11.               
  12.         };  

Stop Music Output

When we run the application, we can see the output from our emulator with newly added Stop Song button in our App

Xamarin

When the user clicks on the Stop Song button the playing song will be stopped.

Xamarin

Increase the Volume

For increase the mobile device or emulator volume, we will create a new button and, in the button click event we will write our code to increase the volume.

Now we will add a button and, in the button click event we will write code to increase the volume.

In our Main.axml file design your button to increase the volume

  1. <Button  
  2.         android:text="Volume ++"  
  3.         android:layout_width="match_parent"  
  4.         android:layout_height="wrap_content"  
  5.         android:id="@+id/button3"  
  6.         android:background="@android:drawable/alert_dark_frame" />  

Add the button click event to increase the volume from our MainActivity.cs and add the below code to increase the volume. Here we will be use the AudioManager and set the volume as Android.Media.Adjust.Raise

  1. //Increase the Mobile Volume  
  2.         AudioManager audios =   (AudioManager)GetSystemService(Context.AudioService);  
  3.   
  4.         Button btn3 = FindViewById<Button>(Resource.Id.button3);  
  5.         btn3.Click += delegate  
  6.         {  
  7.             audios.AdjustStreamVolume(Android.Media.Stream.Music,  
  8.                          Android.Media.Adjust.Raise, Android.Media.VolumeNotificationFlags.PlaySound);   
  9.         };  

Volume Increase Output

When we run the application, we can see the output from our emulator with newly added Volume ++ button in our App we can see the Media volume is set to low now.

Xamarin

When the user clicks on the Volume ++ Button the volume will be slowly increasing and now the Media volume has been set to its maximum sound.

Xamarin

Decrease the Volume

For decrease the mobile device or emulator volume, we will create a new button and, in the button click event we will write our code to decrease the volume.

Now we will add a button and, in the button click event we will write code to decrease the volume.

In our Main.axml file design your button to increase the volume

  1. <Button  
  2.         android:text="Volume --"  
  3.         android:layout_width="match_parent"  
  4.         android:layout_height="wrap_content"  
  5.         android:id="@+id/button4"  
  6.         android:background="@android:drawable/alert_dark_frame" />  

Add the button click event to decrease the volume from our MainActivity.cs and add the below code to decrease the volume. Here we will be use the AudioManager and set the volume as Android.Media.Adjust.Lower

  1.     //Decrease the Mobile Volume  
  2.         Button btn4 = FindViewById<Button>(Resource.Id.button4);  
  3.         btn4.Click += delegate  
  4.         {  
  5. audios.AdjustStreamVolume(Android.Media.Stream.Music,  
  6. ndroid.Media.Adjust.Lower, Android.Media.VolumeNotificationFlags.PlaySound);   
  7.         };   

Volume Decrease Output

When we run the application, we can see the output from our emulator with the newly-added Volume button in our App. We can see the Media volume is set to high now.

Xamarin

When the user clicks on the Volume  Button the volume will be slowly decreasing and now the Media volume has been set to its low sound.

Xamarin

Conclusion

Hope you enjoyed reading this article. Download the source code and change it as per your need and soon we will see more articles related to developing Xamarin mobile apps.


Similar Articles