Monday, July 23, 2018

Counter App

Design for Counter App (Layout File)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
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:orientation="vertical"    
android:padding="16dp"
android:layout_height="match_parent"    
tools:context="net.samaysoftware.sampleapplication12345.MainActivity">
    <TextView
        android:id="@+id/tvNumber"        
        android:layout_width="match_parent"        
        android:layout_height="wrap_content"
        android:textSize="80sp"        
        android:gravity="center"        
        android:text="1" />


    <Button        
        android:id="@+id/btnIncrement"        
        android:layout_width="match_parent"        
        android:layout_height="wrap_content"        
        android:text="Increment" />


    <Button        
        android:id="@+id/btnDecrement"        
        android:layout_width="match_parent"        
        android:layout_height="wrap_content"        
        android:text="Decrement" />


</LinearLayout>


Code for Counter App (Java File)

package net.samaysoftware.sampleapplication12345;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    TextView tvNumber;
    Button btnIncrement, btnDecrement;
    @Override    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvNumber = (TextView)findViewById(R.id.tvNumber);
        btnIncrement = (Button) findViewById(R.id.btnIncrement);
        btnDecrement = (Button) findViewById(R.id.btnDecrement);
        tvNumber.setText("0");
        btnIncrement.setOnClickListener(this);
        btnDecrement.setOnClickListener(this);
        tvNumber.setOnClickListener(this);
    }
    @Override    
    public void onClick(View view) {
        if(view==btnIncrement) {
            String number = tvNumber.getText().toString();
            int no = Integer.parseInt(number);
            no++;
            String newnumber = String.valueOf(no);
            tvNumber.setText(newnumber);
        }else if(view== btnDecrement){
            String number = tvNumber.getText().toString();
            int no = Integer.parseInt(number);
            no--;
            String newnumber = String.valueOf(no);
            tvNumber.setText(newnumber);
        }
        else if(view==tvNumber){
            tvNumber.setText("100");

        }
    }
}

Android Resources

Good Practice to have non code resources as external resources. These include images, String constants, colors, animations, themes, menus  and most powerful ones which are layouts. It makes them easy to manage 
and update external resources. Alternative resources can be easily specified for different hardware configurations, languages, locations. Android automatically selects current resources when application starts. Even after starting the app, layout may be switched based on size and orientation.

How To Create Resources


res folder has all resources. Sub folders for each resource types. Default ones are values, drawable-hdpi, drawable-mdpi, drawable-ldpi, layout. The different resources will be compiled and compressed when the application is built as efficiently as possible. At that time, R.java file is generated which is compiled into R class file that containes references to these resources to be used from your application code.
Names of resource files should contain only lower case letters, numbers and underscore and period only.
1.       Simple Values – strings, colors, dimensions, styles, string/int array. Location: res/values folder.
eg.
res/values/simple_values.xml
<resources>
<string name=”app_name”>To Do List</string> // here you can use <b>, <i>, <u> tags
<plurals name=”androidPlural”>
<item quantity=”one”>One android</item>
<item quantity=”other”>%d androids</item>
</plurals>
<color name=”app_background”>#FF0000FF</color> // #RGB, #RRGGBB, #ARGB, #AARRGGBB are supported
<dimen name=”default_border”>5px</dimen>
<string-array name=“string_array“>
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</string-array>
<array name=“integer_array“>
<item>3</item>
<item>2</item>
<item>1</item>
</array>
</resources>
2.       Styles and Themes – Common attribute values which can be used by multiple views.

<resources>
<style name=”base_text”>
<item name=”android:textSize”>14sp</item>
<item name=”android:textColor”>#111</item>
</style>
<style name=”small_text” parent=”base_text”> // inheritance of style by specifying parent attribute
<item name=”android:textSize”>8sp</item> // overriding old attribute, or redefining new attribute
</style>
</resources>

3.       Drawables – bitmaps, NinePatches (Stretchable PNGs), every drawable in separate individual file
4.       Layouts – Presentation Layer, XML Specification of UI Elements, once defined here, it must be inflated into the UI, by invoking setContentView() method from inside onCreate() method of activity. Folder is res/layout, each layout in separate file,
5.       Animations – Property Animations (3.0 version, res/animator, file name is used as identifier like drawables and layouts, they are extremely used to animate fragments), View Animations(Animating particular Views), Frame Animations (Switch drawables after a particular time).
6.       Menu - res/menu , 1 file for 1 menu
7.        
System Resoucres
In addition to the resources we supply, Android Platform includes several system resources which can be used in Code directly or in other resources. User “android.R.” instead of “R.”. eg. android.R.string.httpErrorBadUrl
<EditText
android:id=”@+id/myEditText”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”@android:string/httpErrorBadUrl”
android:textColor=”@android:color/darker_gray”
/>


How to access resources in code?
Internationalization of resources
Resources r=getResources();
=>We have getter methods for each Resource Type?
r.getDrawable(R.drawable.app_icon);
r.getText(R.string.some_string_name);
r.getColor(R.color.some_color);
r.getStringArray(), r.getIntArray(),

Project/
     res/
          values/
               strings.xml
          values-fr/
               strings.xml
          values-fr-rCA/
               strings.xml

Android Manifest

AndroidManifest.xml – must in every app – stored in root of project hierarchy – Nodes for each component as defined above – Also Permissions – Meta data like Icon, version number, Theme etc. – Hardware screen/ 
platform requirements. By default all apps are installed on internal storage, however we may specify installation on external storage in the manifest tag as an attributeinstallLocation with values preferExternal or auto (If installed on external storage, app will stop when connected to PC as mass storage device to copy files).

Tags in Manifest File:

1.       <manifest></manifest> => Root Level
2.       <uses-sdk android:minSdkVersion =”6” android:targetSdkVersion=”15” />
minSdkVersion: Lowest version of JDK that includes the API you have used. Default value is 1.
Eg. minSdkVersion=”4”, means you are telling it should work on all devices with min version 4 and it should not work on any devices with lesser version
So you cannot install it on device with sdk less than 4, also if sdk greater than 4, and u install successfully, app may crash if you have used some API which needs a higher SDK version. So it must be assigned judiously.
targetSdkVersion: Specify the platform on which you did development and testing. No need to apply any forward or backward compatibility changes on this particular version. Best to update target SDK of your app to newest stable release, even though if you are not using any new APIs because you may get some internal UI improvements.
maxSdkVersion: Upper limit your are supporting, app wont be visible on Google Play for other newer devices. Unnecessary to specify it. And it is ignored during installation after 2.0.1 version. (API level 6)
3.       <uses-configuration> => Specify input devices, not necessarily needed, except games with special keyboards
4.       <uses-feature> => Any hardware required like Audio, Bluetooth, NFC, Camera, Microphone, Sensors, Location, Telephony, USB, Wi-fi etc.
5.       <uses-permission>
6.       <application> specify icon, title, theme, name etc for app, only one such tag allowed.
7.       <activity> 1 such tag for every activity, It has name and label as attributes.
8.       <intent-filter> it is sub tag of activity tag to specify intents that can be used to start this activity.

Key Components of Android App

Types of Android Applications

1.       Foreground – useful only when it is seen and is effectively suspended when in background – ex. Games
2.       Background – Very less UI, mainly for configuration, rest of working in background – ex Auto SMS Responder. We can create completely invisible services also, but it is better to have some basic interation
3.      Intermittent – Some have min UI and do most work in Background ex. Music Player, Some do most work in foreground but do important work in background. ex. Email apps
4.       Widgets and Live Wall Papers

Hardware imposed Design Considerations
1.       Low processing power
2.       Limited RAM.
3.        Limited permanent storage capacity
4.       Small screens with low resolution
5.       High costs associated with data transfer
6.       Intermittent connectivity, slow data transfer rates, and high latency
7.       Unreliable data connections
8.       Limited battery life

Developing for Android needs following

1.Being fast and efficient (in resource constrained environment, fast=efficient)  -2. Being Responsive (If ActivityManager or WindowManager finds any activity or window to be non-responsive/slow, it shows dialog of force close to the user, max response time for clicks is 5 sec) –3.Ensuring Data Freshness (Multitasking is a key feature which means data changes in background. When to look for new data to UI? just before displaying it.) -  4.Developing Secure Apps (Declaration of permissions needed, each app is sandboxed separately) – 5.Ensuring a Seam Less User Experience (Apps start, stop and transit without delays or jarring effects with time) –6.Providing Accessibility (Don’t assume every user will be like you, same as accessibility in java)

What all comprises an Android Application

Loosely coupled components, bound by the application manifest that describes each component and how they interact. Manifest also specifies the apps hardware and platform requirements, external libraries, permissions.
Following are building blocks of an android app:
Activities – Presentation layer of your applike Forms or Pages or Screens. Services – Invisible workers of your app, without UI, but update the data sources of activities, trigger Notifications and broadcasting intents. Typically long running tasks. Content Providers – Shareable Persistent Data storage, manage data and interact with SQL DBs and share data across application boundaries. You can configure CPs to allow other apps to access your data, or use the CPs of other apps. Intents –Powerful message passing framework. Broadcast Receivers – To listen for intents that match to your criteria you specify. Much used for event-driven applications. Widgets – Visual app components added to home screen. Notifications – Alert the users to app events without disturbing current activity. It is typically used to get User Attention from within Service or Broadcast Receiver. 

What is Android?

What is Android?

Android is an open-source software stack that includes the operating system, middleware, and key 
mobile applications, along with a set of API libraries for writing applications that can shape the look, feel, and function of the devices on which they run. With the introduction of tablets and Google TV, Android has expanded beyond its roots as a mobile phone operating system, providing a consistent platform for application development across an increasingly wide range of hardware.

Android is an eco-system of 3 things – free Open Source OS (OSOS) for embedded devices – An OS Development Platform for Apps – Devices that run Android OS and Apps created for it. 

Why Android is Famous?


Android has powerful APIs, excellent documentation, a thriving developer community, and no development or distribution costs. As mobile devices continue to increase in popularity, and Android devices expand into exciting new form-factors, you have the opportunity to create innovative applications no matter what your development experience.

History of Mobile Devices

In the days before Twitter and Facebook, when Google was still a twinkle in its founders’ eyes and dinosaurs roamed the earth, mobile phones were just that — portable phones small enough to fit inside a briefcase, featuring batteries that could last up to several hours. They did, however, offer the freedom to make calls without being physically connected to a landline.

Increasingly small, stylish, and powerful, mobile phones are now ubiquitous and indispensable. Hardware advancements have made mobiles smaller and more effi cient while featuring bigger, brighter screens and including an increasing number of hardware peripherals.

After fi rst including cameras and media players, mobiles now feature GPS receivers, accelerometers, NFC hardware, and high-defi nition touchscreens. These hardware innovations offer fertile ground for software development, but until relatively recently the applications available for mobile phones have lagged behind their hardware counterparts.

Mobile Application History
C/C++ coding in specific hardware which was targeted – Later on came platforms like Symbian, allowed target target devices -  Still accessing the device hardware needed lot of complex C/C++ programming. Biggest Advancement came with Java hosted MIDlets. IT defines an architecture that abstracts the underlying hardware & lets the developer develop application targetted to multiple devices – Only Drawback with MIDlets was it dint give low level hardware access and sandbox model prevented lot of things making a MIDlet like a simple desktop application or a mobile version of Website. Rather what was required was to make advantage of the inherent mobility of the handheld device. 

Minimum Native Android Apps (A suite of preinstalled apps as part of AOSP- Android Open Source Project)
1.       Email Client
2.       SMS mgmt app
3.       PIM – Personal Information Mgmt including calendar, contact lists
4.       WebKit-based Browser
5.       Music Player
6.       Picture Gallery
7.       Camera & Video Recording App
8.       Calculator
9.       A Home Screen
10.   An Alarm Clock
Additional Apps given sometimes
1.       Google Play
2.       Google Maps Application fully featured for navigation and directions
3.       Gmail email client
4.       Google Talk – instant messaging Client
5.       Youtube player
Android SDK Features (Lot of APIs)
GSM, 3G, SMS – GPS (Location Based Services), Maps, Geocoding – Wifi hardware access – Full multimedia hardware control including playback, recording with camera/microphone – Media Libraries to play and record audio/video/images – APIs for SENSOR Hardware including Accelerometers/barometers/compasses – Bluetooth , NFC – IPC Message passing – APIs for contacts, Social Networking, calendar – Background Services, apps, processes – Home Screen Widgets and Live Wallpapers – Integrated OS WebKit – based browser, path-based 2D graphics, OpenGL 3D graphics – Localization using dynamic resource framework – An application framework to replace native apps and reuse existing apps.

Why Develop for mobile and why not think of reusing the desktop apps in mobile?
The ubiquity of mobile phones, and our attachment to them, makes them a fundamentally different platform for development from PCs. Smartphone applications has changed the way people use their phones. This gives you, the application developer, a unique opportunity to create dynamic, compelling new applications that become a
vital part of people’s lives.

Why Develop for Android ?
Open Source, by Developers – for developers – no certi required to become android developer – no approval needed in distributing your apps – easy monetizing and upfront payment on Google Play – Total control of brand is with developers.

Why Prefer over other platforms?
Things that android has which most other mobile platforms do not have or are very complex in them: Google Map applications – Background services and applications – IPC – All applications are equal – Wifi Direct and Android BEAM – Home Screen Widgets, Live Screen Wallpapers & Quick Search Box

THE WHY COMPLETES HERE, NOW WE COME TO HOW

Programming Language: Java
If you have experience with java you will find syntax, grammar, techniques, they would directly translated into Android, although some of the optimization techniques may be counter intuitive

Execution is by custom VM: Dalvik VM rather than traditional JVM. It is a middle tier between apps and hardware. Thus apps implemented over DVM need not worry about particular underlying device implementation. Dalvik executable files are executed by DVM. Thus on compilation, .java files are converted into .dex by converting the bytecode into dalvic executable using tools available in SDK.Should we develop android apps on Windows or Linux or Mac? Since it runs on DVM, there is no particular advantage of developing on any particular OS.

What is below DVM? It’s a Linux 2.6 Kernel that handles low level hardware interactions – drivers, process, memory, security, network, power

Android Runtime = Core Libraries (core java and android libraries) + DVM
If we do not have Android runtime, the android phone would rather be a simple mobile linux implementation

Application Framework = provides classes to write android apps. It is abstraction of hardware/UI/resources


Application Layer = All native & 3rd party Apps which makes use of Application Framework classes and services

Near by App

https://drive.google.com/file/d/0B2ag35s4X53Eb2pSQVI1SzNudE0/view