Android 101: Running Your First Android Application

Understanding the Hello World App


In my earlier Post i have talked about some basic concepts and how to create your first app. Now we are going to Understand various files and resources that a android Application contains.

In android studio this is how our Hello World project structure looks like.We will be discussing only important terms right now so you guys don’t get confused. Here is the marked things that now we going to understand step by step.

  •  Android manifest :- A manifest is most important part in android application. It represents the information about your application to the android system without it, it’s not possible to run your application on any android device. This do contains things like permissions, main & other activities, packages, icons and labels, libraries any many more thing. you can read more about manifest here. In our “Hello World” application manifest looks like this.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.design.vikaskumar.helloworld" > 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application> 
</manifest>

The manifest file starts with manifest tag and ends with tag closed <manifest>…….</manifest>. Everything comes inside the manifest file, like above the <application> tag contains the application’s icon and label that will be shown in app drawer  which further contains the <activity>.

<activity
 android:name=".MainActivity"   
 android:label="@string/app_name"
 android:theme="@style/AppTheme.NoActionBar" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>

android:name property is the name of the “.MainActivity” (java file) that will be called when application will be launch first.

android:Label property shows the applications name in our case its “hello world”.

android:theme   property used to give theme, basically a color scheme for the activity alone.

Next is <intent-filter> which is used to do some action like calling some activity and many more things with intent, which we will be covering later. For now android:name=”android.intent.action.MAIN” property tells system to treat the parent activity as a entry point for application. It is used with android:name=”android.intent.category.LAUNCHER” property to show up in system’s application list.

MainActivity :- MainActivity is basically a java file which will be called first on application start up as i earlier stated. Keep a look at our mainactivity file of hello world to understand the basic methods. You can use this main activity  to do something which you want your app to do on start up like splash screen or some animations and most important building the GUI part of the app. Have a look at MainActivity file below.

package com.design.vikaskumar.helloworld;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

       FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

In above code MainActivity is the name of the Activity which is extending the AppCompatActivity (a support library) for using action bar features.

This method is like constructor which initiates the start up activities and saves other data in Bundle so that data don’t get lost while switching from the portrait to landscape and vice versa. If you don’t save the activity state using Bundle, activity will be reset and data may loss. This is the first method get’s called when app is launched so by default we use it to do task like setting the layout, initialization of the data and many more things .

protected void onCreate(Bundle savedInstanceState) {...}

As we have set the layout of the activity with  setContentView(R.layout.activity_main),  and activity Toolbar using Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar). If you want to learn more about the activity go here.

res :- Next we have resources folder which contains the various resources like vector images, xml files, animations, audio or video, layouts etc. drawable folder under res folder contains the image or xml assests. In our Hello world app the layout used is based on material design so we are not going to touch until we master ourself with basics. But we will be covering this in coming tutorials about material designs. Here i am going to tell only the basics which matters to us right now.

activity_main.xml layout is given below :-

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.design.vikaskumar.helloworld.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Let’s understand how things are related to each other in layout and actual output.

content_main.xml contains our actual data hello world in a TextView which is included in activity_main using the xml tag <include layout=”@layout/content_main”/>, the layout is given by.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main"
    tools:context="com.design.vikaskumar.helloworld.MainActivity">

    <TextView
        android:text="Hello World!"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

The Values folder under the res folder contains the string, colors, dimens, styles, strings, resources which we need in our app. Right now we are going to have a quick look at.

strings.xml :- In this xml file we store the strings which we use at different places in the app like “HelloWorld” string in AndroidManifest.xml file above  with android:label=”@string/app_name” here @string (used to refer the strings.xml file) and  /app_name (is the name of the string or you can say it’s a id to point at a particular string in strings.xml file). The string resource file is given by.

<resources>
    <string name="app_name">HelloWorld</string>
    <string name="action_settings">Settings</string>
</resources>

build.gradle :- Before we get into the gradle file it’s important to know what gradle does in android studio. Gradle is project management system used to build, run, test and package your apps. I think you should go here to get informed about gradle file system. Android Studio does all things automatically but the one file from gradle you may need sometimes is explained below.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.design.vikaskumar.helloworld"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}

The compileSdkVersion 23 makes our app compatible and run upto api version 23 (marshmallow). It’s a API version against you compile your application.

The buildToolsVersion 23.0.2 shows the version of android tools like (aapt,dex,renderscript compiler,aidl etc) we have used to build our application.
The applicationId “com.design.vikaskumar.helloworld” is a unique id of your application .which is useful when you deploy your application on play store where millions of applications present so definitely you need something unique, can be called as signature of your application. You can name it accordingly your name or company domain, anything but unique.

The minSdkVersion 15 shows the minimum android API version you want your application to support like we have set this to 15 which correspond to ICS (ice cream sandwich), our application can run onto devices with ICS but can not be support later devices with Honeycomb and Gingerbread and so on.

The targetSdkVersion 23 represents the maximum API version your application supports. It may Work on API 24 until it uses some feature which your application do not support ,may crash.

The versionCode 1  & versionName “1.0” is useful when you upgrade your application at play store from your developer console. Each time you update
your application you just increase the version code and change version name.

The compile ‘com.android.support:appcompat-v7:23.1.1’  is project dependencies ,we need to compile. Without it our project will not compile as our app uses the features of appcompat support library. We can also add other library using compile ‘library name’ . We have to make sure the library we are going to use supports the gradle based compilation.

Debugging the Application

Well it’s time to debug the application and see the actual output what we were cooking from a long time.There is two way either we use the virtual device or the actual android device with USB. First we will be creating a AVD.

Steps to create AVD (android virtual device)

  • Go to tools->Android->Avd Manager.
  • Click on + create virtual device.
  • select the hardware, like we have selected nexus 5 and click on next button.
  • Choose the downloaded system image and click next.
  • if you have not downloaded the system images please open the Tools -> Android -> SDK Manager and download the latest system images.
  • Verify the configurations at last and click finish. Once AVD created, debug your application by pressing shift+f9.
Now those who do have a physical android device follow the following steps.

  • Go to settings -> About phone -> Build number (click 7 times) and developers options will be visible.
  • Go to developers options and turn it on, also enable USB debugging.

Now, May be you need USB drivers to detect the android device on debug. Well motorola users can go here, samsung folks can download drivers here, HTC users can go here, others can download this tool here and simply install it. Google nexus devices works fine after downloading the google USB drivers in SDK manager. You can read about OEM USB drivers more here.

Final output after running application


Please share this post if you find this helpful and please do email me or comment below in case if you got any problem. I will be happy to help. If you are all clear then follow the next tutorial, lets find out what next do we have for you.

Comments

Popular Posts