Tuesday, January 14, 2014

Learning Android Studio

An activity is an instance of Activity, a class in the Android SDK. An activity is responsible for managing user
interaction with a screen of information.

Alt + 1 to open the project view
drawable/: A folder that contains the images used in our application. There are different drawable folders categorized into the different screen densities.

layout/: A folder that contains the XML definitions of the views and their elements.
menu/: A folder that contains the XML definitions of the menus of the application.
values/: A folder that contains the XML files that define sets of name-value pairs. There are different values folders categorized into different screens options to adapt the interface to them.
AndroidManifest.xml: This file declares basic information needed by the Android system to run the application, package name, version, activities, permissions, intents, or required hardware.
build.gradle: This file is the script used to build our application.

Editor settings
Change font size (Zoom) with Ctrl + Mouse Wheel.
Show quick doc on mouse move.

Appearance
Show line numbers
Show method separators

Editor Tabs:
Select the Mark modified tabs with asterisk option to easily detect the modified and not-saved files.

Auto Import:
Add unambiguous imports on the fly

Code completion: Ctrl+Space
To open the smart suggestions list, press Ctrl + Shift + the Spacebar.
Completion of statements. Type a statement, press Ctrl + Shift + Enter.

Code generation: 
Code | Generate: Alt + Insert
Code | Surround With or press Ctrl + Alt + T
Code | Insert Live Templates to open a dialog box of the available templates. 

Navigating code
Press Ctrl and click on the symbol or Navigate | Declaration

custom region is just a piece of code that you want to group and give a name to. For example, if there is a class with a lot of methods, we can create some custom regions to distribute the methods among them. A region has a name or description and it can be collapsed or expanded using code folding.

Useful actions
Ctrl + W: Selects the expressions based on grammar. Keep pressing these keys again and again to expand the selection. The opposite command is Ctrl + Shift + W.
Ctrl + /: Comments each line of the selected code. To use block comments press Ctrl + Shift + /.
Ctrl + Alt + O: Optimizes the imports, removing the unused ones and reordering the rest of them.
Alt + Arrows: Switches between the opened tabs of the editor.
Ctrl + F: Finds a string in the active tab of the editor.
Ctrl + R: Replaces a string in the active tab of the editor.
Ctrl + D: Copies the selected code and pastes it at the end of it. If no code is selected, then the entire line is copied and pasted in a new line.
Ctrl + Y: Removes the entire line without leaving any blank line.
Ctrl + Shift + U: Toggles case.
Tab: Moves to the next parameter.

Creating User Interfaces
To switch between the graphical and the text editor, click on the bottom tabs, Design and Text.

Layouts: A layout is a container object to distribute the components on the screen. The root element of a user interface is a layout object, but layouts can also contain more layouts, creating a hierarchy of components structured in layouts. The recommendation is to keep this layout hierarchy as simple as possible. Our main layout has a relative layout as a root element.
Containers: These are containers group components that share a common behavior. Radio groups, list views, scroll views, or tab hosts are some of them.

Creating a new layout
click with the right mouse button on the layouts folder (res/layout/) and navigate to New | Layout resource file. You can also navigate to the menu option File | New | Layout resource file.
in the toolbar of the layout editor, search for the activity option, click on it, and select the Associate with other Activity option.

layout:width: Its current value is wrap_content. This option will adapt the width of the field to its content. Change it to match_parent to adapt it to the parent layout width (the root relative layout).

Center horizontally the button in the parent layout using the layout_centerHorizontal property. 

Supporting multiple screens
The device definitions indicate the screen inches, the resolution, and the screen density. Android divides into ldpi, mdpi, hdpi, xhdpi, and even xxhdpi the screen densities.

ldpi (low-density dots per inch): About 120 dpi
mdpi (medium-density dots per inch): About 160 dpi
hdpi (high-density dots per inch): About 240 dpi
xhdpi (extra-high-density dots per inch): About 320 dpi
xxhdpi (extra-extra-high-density dots per inch): About 480 dpi

device orientation: landscape  or portrait
Create Landscape Variation
A new layout will be opened in the editor. This layout has been created in the resources folder, under the directory layout-land and using the same name as the portrait layout: /src/main/res/layout-land/activity_main.xml. 

imilarly, we can create a variation of the layout for xlarge screens. Select the option Create layout-xlarge Variation. The new layout will be created in the layout-xlarge folder: /src/main/res/layout-xlarge/activity_main.xml. Android divides into small, normal, large, and xlarge the actual screen sizes:

small: Screens classified in this category are at least 426 dp x 320 dp
normal: Screens classified in this category are at least 470 dp x 320 dp
large: Screens classified in this category are at least 640 dp x 480 dp
xlarge: Screens classified in this category are at least 960 dp x 720 dp
A dp is a density independent pixel, equivalent to one physical pixel on a 160 dpi screen.

in the toolbar click on the configuration option and select the option Preview All Screen Sizes, or click on the Preview Representative Sample to open just the most important screen sizes.
Save screenshot option, which allows us to take a screenshot of the layout preview.

If we create some layout variations, we can preview all of them selecting the option Preview Layout Versions.

Changing the UI theme
Styles and themes are created as resources under the /src/res/values.
Open the main layout using the graphical editor. The selected theme for our layout is indicated in the toolbar: AppTheme. This theme was created for our project and can be found in the styles file (/src/res/values/styles.xml). Open the styles file and notice that this theme is an extension of another theme (Theme.Light).

The selected theme for our layout is indicated in the toolbar: AppTheme. This theme was created for our project and can be found in the styles file (/src/res/values/styles.xml)
The themes created in our own project are listed in the Project Themes section. The section Manifest Themes shows the theme configured in the application manifest file (/src/main/AndroidManifest.xml). The All section lists all the available themes. 

All the UI widgets are children of the View class and they share some events handled by the next listeners:
OnCreateContextMenu: Captures the event when the user performs a long click on the view element and we want to open a context menu
OnTouchListener: Captures the event when the user touches the view element
public void onAcceptClick(View v) {
  TextView tv_greeting =
    (TextView) findViewById(R.id.textView_greeting);
  EditText et_name = (EditText) findViewById(R.id.editText_name);

  if(et_name.getText().length() > 0) {
    tv_greeting.setText("Hello " + et_name.getText());
  }
}
The R class is autogenerated in the build phase and we must not edit it. If this class is not autogenerated, then probably some file of our resources contains an error.

In case the event we want to handle is not the user click, then we have to create and add the listener by code in the onCreate method of the activity.

Adding Google Play Services to Android Studio
Tools | Android | SDK Manager. We can find Google Play Services in the packages list under the folder Extras. Select the Google Play Services checkbox and click on the Install 1 package... button.
/sdk/extras/google/google_play_services/

Add this JAR file to your project by just dragging it into the libs/ folder. Once this is done, select the JAR file and press the right mouse button on it. Select the Add as Library option. In the create library dialog, select the project library level, select your application module, and click on OK.

Finally, you will need to add the library to your Gradle's build file. To do this just edit the file MyApplication/build.gradle and add the following line in the dependencies section:

compile files('libs/google-play-services.jar')

Click on File | Import Project.

Tools | Android | SDK Manager
The Software Development Kit (SDK) Manager is an Android tool integrated in Android Studio to control our Android SDK installation. From this tool we can examine the Android platforms installed in our system, update them, install new platforms, or install some other components such as Google Play Services or the Android Support Library.

Android Virtual Device Manager
The Android Virtual Device Manager (AVD Manager) is an Android tool integrated in Android Studio to manage the Android virtual devices that will be executed in the Android emulator.

Emulation Options: The Snapshot option saves the state of the emulator in order to load faster the next time. Check it. The Use Host GPU option tries to accelerate the GPU hardware to run the emulator faster.

Tools | Generate Javadoc
VCS | Enable Version Control Integratio

Device Definitions | New Device
Waiting for device: Start point when the emulator is being launched.
Uploading file: The application is packed and stored in the device.
Installing: The application is being installed in the device. After the installation a success message should be printed.
Launching application: The application starts to execute.
Waiting for process: The application should now be running and the debug system tries to connect to the application process in the device.
To execute the next line of code without stepping into the method call, navigate to Run | Step Over or use the keyboard shortcut indicated for this option, usually key F8
To step into the method call, navigate to Run | Step Into or press F7
To resume the execution until the next breakpoint if there is one, navigate to Run | Resume Program or press F9
To stop the execution, navigate to Run | Stop or press Ctrl + F2

LogCat is the Android logging system that displays all the log messages generated by the Android system in the running device.
v method for debug level, d method for verbose, i method for information, w method for warning, and e method for error messages. 
Log.w("MainActivity", "No name typed, greeting didn't change");
Edit Filter Configuration
Log messages can be filtered by their tag or their content using regular expressions, by the name of the package that printed them, by the process ID (PID), or by their level.

DDMS
The Dalvik Debug Monitor Server (DDMS) is a more advanced debugging tool from the SDK that has also been integrated into Android Studio. This tool is able to monitor both a real device and the emulator.
Tools | Android | Monitor (DDMS included)

Click on the Update Threads icon button from the toolbar of the devices section and the threads will be loaded in the content of the tab.

Preparing for Release
APK (Application Package) file
Android applications are packed in a file with the .APK extension, which is a variation of a Java JAR (Java Archive) file. These files are just compressed ZIP files, so their content can be easily explored. An APK file usually contains:

assets/: A folder that contains the assets files of the application. This is the same assets folder existing in the project.
META-INF/: A folder that contains our certificates.
lib/: A folder that contains compiled code if necessary for a processor.
res/: A folder that contains the application resources.
AndroidManifest.xml: The application manifest file.
classes.dex: A file that contains the application compiled code.
resources.arsc: A file that contains some precompiled resources.

check the Unknown sources option from the Settings | Security
Applications have to be signed with a private key when they are built. An application can't be installed in a device or even in the emulator if it is not signed. To build our application there are two modes, debug and release. Both APK versions contain the same folders and compiled files. The difference is the key used to sign them:

Debug: The Android SDK tools automatically create a debug key, an alias, and their passwords to sign the APK. This process occurs when we are running or debugging our application with Android Studio without us realizing that. We can't publish an APK signed with the debug key created by the SDK tools.
Release:It is a requirement that the APK file is signed with a certificate for which the developer keeps the private key. In this case, we need our own private key, alias, and password and provide them to the build tools. The certificate identifies the developer of the application and can be a self-signed certificate. It is not necessary for a certificate authority to sign the certificate.

Previous steps
On a device using the minimum required platform
On a device using the target platform
On a device using the latest available platform
On a real device and not just in the emulator
On a variety of screen resolutions and sizes
On a tablet if your application supports them
Switching to the landscape mode if you allow it, both in a mobile device and in a tablet
On different network conditions, such as no Internet connectivity or low coverage
If your application uses the GPS or any location service, test it when they are not activated in the device
Behavior of the back button

Printing some log messages can be considered a security vulnerability. Logs generated by the Android system can be captured and analyzed, so we should avoid showing critical information about the application's internal working. You should also remove the android:debuggable property from the application manifest file. You can also set this property to false.

Finally, set the correct value for the android:versionCode and android:versionName properties from the application manifest file. The version code is a number (integer) that represents the application version. New versions should have greater version codes. This code is used to determine if an application installed in a device is the last version, or there is a newer one.

The version name is a string that represents the application version. Unlike the version code, the version name is visible to the user and appears in the public information about the application. It is just an informative version name to the user and is not used for any internal purpose.

Generating a signed APK
Build | Generate Signed APK.
Create new button to open the dialog box to create a new key store.
Alias: Alias for your certificate and pair of public and private key. For example, name it as releasekey.

Choose existing

For gradle build:
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Signing-Configurations

1 comment:

  1. Trutech Products has been at cutting edge in giving exclusively based Transformer answers for its extensive variety of customer base. Our huge client base is a confirmation and a wellspring of inspiration towards our conviction of being straightforward and inventive in our business rehearses.

    Transformer manufacturers in India
    isolation transformer manufacturers

    ReplyDelete