Android – Questions and Answers

Android Questions and Answers ”; Previous Next Android Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 Android Interview Questions This section provides a huge collection of Android Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Android Online Quiz This section provides a great collection of Android Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Android Online Test If you are preparing to appear for a Java and Android Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Android Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;

Android – ProgressBar

Android Progress Bar using ProgressDialog ”; Previous Next Progress bars are used to show progress of a task. For example, when you are uploading or downloading something from the internet, it is better to show the progress of download/upload to the user. In android there is a class called ProgressDialog that allows you to create progress bar. In order to do this, you need to instantiate an object of this class. Its syntax is. ProgressDialog progress = new ProgressDialog(this); Now you can set some properties of this dialog. Such as, its style, its text etc. progress.setMessage(“Downloading Music đŸ™‚ “); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setIndeterminate(true); Apart from these methods, there are other methods that are provided by the ProgressDialog class Sr. No Title & description 1 getMax() This method returns the maximum value of the progress. 2 incrementProgressBy(int diff) This method increments the progress bar by the difference of value passed as a parameter. 3 setIndeterminate(boolean indeterminate) This method sets the progress indicator as determinate or indeterminate. 4 setMax(int max) This method sets the maximum value of the progress dialog. 5 setProgress(int value) This method is used to update the progress dialog with some specific value. 6 show(Context context, CharSequence title, CharSequence message) This is a static method, used to display progress dialog. Example This example demonstrates the horizontal use of the progress dialog which is in fact a progress bar. It display a progress bar on pressing the button. To experiment with this example, you need to run this on an actual device after developing the application according to the steps below. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add progress code to display the progress dialog. 3 Modify res/layout/activity_main.xml file to add respective XML code. 4 Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.ProgressDialog; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends ActionBarActivity { Button b1; private ProgressDialog progress; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button2); } public void download(View view){ progress=new ProgressDialog(this); progress.setMessage(“Downloading Music”); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setIndeterminate(true); progress.setProgress(0); progress.show(); final int totalProgressTime = 100; final Thread t = new Thread() { @Override public void run() { int jumpTime = 0; while(jumpTime < totalProgressTime) { try { sleep(200); jumpTime += 5; progress.setProgress(jumpTime); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; t.start(); } } Modify the content of res/layout/activity_main.xml to the following − <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” 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” tools:context=”.MainActivity”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textView” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:textSize=”30dp” android:text=”Progress bar” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials Point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:textSize=”35dp” android:textColor=”#ff16ff01″ /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Download” android:onClick=”download” android:id=”@+id/button2″ android:layout_marginLeft=”125dp” android:layout_marginStart=”125dp” android:layout_centerVertical=”true” /> </RelativeLayout> This is the default AndroidManifest.xml − <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run your application. We assume, you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application. Select your mobile device as an option and then check your mobile device which will display following screen − Just press the button to start the Progress bar. After pressing, following screen would appear − It will continuously update itself. Print Page Previous Next Advertisements ”;

Android – ImageSwitcher

Android – Image Switcher ”; Previous Next Sometimes you don”t want an image to appear abruptly on the screen, rather you want to apply some kind of animation to the image when it transitions from one image to another. This is supported by android in the form of ImageSwitcher. An image switcher allows you to add some transitions on the images through the way they appear on screen. In order to use image Switcher, you need to define its XML component first. Its syntax is given below − <ImageSwitcher android:id=”@+id/imageSwitcher1″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_centerHorizontal=”true” android:layout_centerVertical=”true” > </ImageSwitcher> Now we create an intance of ImageSwithcer in java file and get a reference of this XML component. Its syntax is given below − private ImageSwitcher imageSwitcher; imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher1); The next thing we need to do implement the ViewFactory interface and implement unimplemented method that returns an imageView. Its syntax is below − imageSwitcher.setImageResource(R.drawable.ic_launcher); imageSwitcher.setFactory(new ViewFactory() { public View makeView() { ImageView myView = new ImageView(getApplicationContext()); return myView; } } The last thing you need to do is to add Animation to the ImageSwitcher. You need to define an object of Animation class through AnimationUtilities class by calling a static method loadAnimation. Its syntax is given below − Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left); imageSwitcher.setInAnimation(in); imageSwitcher.setOutAnimation(out); The method setInAnimaton sets the animation of the appearance of the object on the screen whereas setOutAnimation does the opposite. The method loadAnimation() creates an animation object. Apart from these methods, there are other methods defined in the ImageSwitcher class. They are defined below − Sr.No Method & description 1 setImageDrawable(Drawable drawable) Sets an image with image switcher. The image is passed in the form of bitmap 2 setImageResource(int resid) Sets an image with image switcher. The image is passed in the form of integer id 3 setImageURI(Uri uri) Sets an image with image switcher. THe image is passed in the form of URI 4 ImageSwitcher(Context context, AttributeSet attrs) Returns an image switcher object with already setting some attributes passed in the method 5 onInitializeAccessibilityEvent (AccessibilityEvent event) Initializes an AccessibilityEvent with information about this View which is the event source 6 onInitializeAccessibilityNodeInfo (AccessibilityNodeInfo info) Initializes an AccessibilityNodeInfo with information about this view Example The below example demonstrates some of the image switcher effects on the bitmap. It crates a basic application that allows you to view the animation effects on the images. To experiment with this example , you need to run this on an actual device. Steps Description 1 You will use Android studio IDE to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components 4 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified main activity file src/MainActivity.java. In the below code tp and abc indicates the logo of tutorialspoint.com package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.app.ActionBar.LayoutParams; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.Toast; import android.widget.ViewSwitcher.ViewFactory; public class MainActivity extends Activity { private ImageSwitcher sw; private Button b1,b2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); b2 = (Button) findViewById(R.id.button2); sw = (ImageSwitcher) findViewById(R.id.imageSwitcher); sw.setFactory(new ViewFactory() { @Override public View makeView() { ImageView myView = new ImageView(getApplicationContext()); myView.setScaleType(ImageView.ScaleType.FIT_CENTER); myView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); return myView; } }); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), “previous Image”, Toast.LENGTH_LONG).show(); sw.setImageResource(R.drawable.abc); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), “Next Image”, Toast.LENGTH_LONG).show(); sw.setImageResource(R.drawable.tp); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” 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” tools:context=”.MainActivity”> <TextView android:text=”Gestures Example” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textview” android:textSize=”35dp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35dp” /> <ImageSwitcher android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageSwitcher” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:layout_marginTop=”168dp” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/left” android:id=”@+id/button” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/right” android:id=”@+id/button2″ android:layout_alignParentBottom=”true” android:layout_alignLeft=”@+id/button” android:layout_alignStart=”@+id/button” /> </RelativeLayout> Following is the content of Strings.xml file. <resources> <string name=”app_name”>My Application</string> <string name=”left”><![CDATA[<]]></string> <string name=”right”><![CDATA[>]]></string> </resources> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” <application android:allowBackup=”true” android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”com.example.sairamkrishna.myapplication.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run your application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − Now if you will look at your device screen , you will see the two buttons. Now just select the upper button that right arrow. An image would appear from right and move towards left. It is shown below − Now tap on the below button, that will bring back the previous image with some transition. It is shown below − Print Page Previous Next Advertisements ”;

Android – Home

Android Tutorial PDF Version Resources Job Search Discussion Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. This tutorial will teach you basic Android programming and will also take you through some advance concepts related to Android application development. Audience This tutorial has been prepared for the beginners to help them understand basic Android programming. After completing this tutorial you will find yourself at a moderate level of expertise in Android programming from where you can take yourself to next levels. Prerequisites Android programming is based on Java programming language so if you have basic understanding on Java programming then it will be a fun to learn Android application development. Print Page Previous Next Advertisements ”;

Android – Activities

Android – Activities ”; Previous Next An activity represents a single screen with a user interface just like window or frame of Java.Android activity is the subclass of ContextThemeWrapper class. If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function. Very similar way, Android system initiates its program with in an Activity starting with a call on onCreate() callback method. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity as shown in the below Activity life cycle diagram: (image courtesy : android.com ) The Activity class defines the following call backs i.e. events. You don”t need to implement all the callbacks methods. However, it”s important that you understand each one and implement those that ensure your app behaves the way users expect. Sr.No Callback & Description 1 onCreate() This is the first callback and called when the activity is first created. 2 onStart() This callback is called when the activity becomes visible to the user. 3 onResume() This is called when the user starts interacting with the application. 4 onPause() The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed. 5 onStop() This callback is called when the activity is no longer visible. 6 onDestroy() This callback is called before the activity is destroyed by the system. 7 onRestart() This callback is called when the activity restarts after stopping it. Example This example will take you through simple steps to show Android application activity life cycle. Follow the following steps to modify the Android application we created in Hello World Example chapter − Step Description 1 You will use Android studio to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. 2 Modify main activity file MainActivity.java as explained below. Keep rest of the files unchanged. 3 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity file src/com.example.helloworld/MainActivity.java. This file includes each of the fundamental life cycle methods. The Log.d() method has been used to generate log messages − package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.util.Log; public class MainActivity extends Activity { String msg = “Android : “; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(msg, “The onCreate() event”); } /** Called when the activity is about to become visible. */ @Override protected void onStart() { super.onStart(); Log.d(msg, “The onStart() event”); } /** Called when the activity has become visible. */ @Override protected void onResume() { super.onResume(); Log.d(msg, “The onResume() event”); } /** Called when another activity is taking focus. */ @Override protected void onPause() { super.onPause(); Log.d(msg, “The onPause() event”); } /** Called when the activity is no longer visible. */ @Override protected void onStop() { super.onStop(); Log.d(msg, “The onStop() event”); } /** Called just before the activity is destroyed. */ @Override public void onDestroy() { super.onDestroy(); Log.d(msg, “The onDestroy() event”); } } An activity class loads all the UI component using the XML file available in res/layout folder of the project. Following statement loads UI components from res/layout/activity_main.xml file: setContentView(R.layout.activity_main); An application can have one or more activities without any restrictions. Every activity you define for your application must be declared in your AndroidManifest.xml file and the main activity for your app must be declared in the manifest with an <intent-filter> that includes the MAIN action and LAUNCHER category as follows: <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.tutorialspoint7.myapplication”> <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”> <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app icon will not appear in the Home screen”s list of apps. Let”s try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display Emulator window and you should see following log messages in LogCat window in Android studio − 08-23 10:32:07.682 4480-4480/com.example.helloworld D/Android :: The onCreate() event 08-23 10:32:07.683 4480-4480/com.example.helloworld D/Android :: The onStart() event 08-23 10:32:07.685 4480-4480/com.example.helloworld D/Android :: The onResume() event Let us try to click lock screen button on the Android emulator and it will generate following events messages in LogCat window in android studio: 08-23 10:32:53.230 4480-4480/com.example.helloworld D/Android :: The onPause() event 08-23 10:32:53.294 4480-4480/com.example.helloworld D/Android :: The onStop() event Let us again try to unlock your screen on the Android emulator and it will generate following events messages in LogCat window in Android studio: 08-23 10:34:41.390 4480-4480/com.example.helloworld D/Android :: The onStart() event 08-23 10:34:41.392 4480-4480/com.example.helloworld D/Android :: The onResume() event Next, let us again try to click Back button on the Android emulator and it will generate following events messages in LogCat window in Android studio and this completes the Activity Life Cycle for an Android Application. 08-23 10:37:24.806 4480-4480/com.example.helloworld D/Android :: The onPause() event 08-23 10:37:25.668 4480-4480/com.example.helloworld D/Android :: The onStop() event 08-23 10:37:25.669 4480-4480/com.example.helloworld D/Android :: The onDestroy() event Print Page Previous Next Advertisements ”;

Android – Intents/Filters

Android – Intents and Filters ”; Previous Next An Android Intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service. The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed. For example, let”s assume that you have an Activity that needs to launch an email client and sends an email using your Android device. For this purpose, your Activity would send an ACTION_SEND along with appropriate chooser, to the Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send your email data. Intent email = new Intent(Intent.ACTION_SEND, Uri.parse(“mailto:”)); email.putExtra(Intent.EXTRA_EMAIL, recipients); email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString()); email.putExtra(Intent.EXTRA_TEXT, body.getText().toString()); startActivity(Intent.createChooser(email, “Choose an email client from…”)); Above syntax is calling startActivity method to start an email activity and result should be as shown below − For example, assume that you have an Activity that needs to open URL in a web browser on your Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the Android Intent Resolver to open given URL in the web browser. The Intent Resolver parses through a list of Activities and chooses the one that would best match your Intent, in this case, the Web Browser Activity. The Intent Resolver then passes your web page to the web browser and starts the Web Browser Activity. String q = “tutorialspoint”; Intent intent = new Intent(Intent.ACTION_WEB_SEARCH ); intent.putExtra(SearchManager.QUERY, q); startActivity(intent); Above example will search as tutorialspoint on android search engine and it gives the result of tutorialspoint in your an activity There are separate mechanisms for delivering intents to each type of component − activities, services, and broadcast receivers. Sr.No Method & Description 1 Context.startActivity() The Intent object is passed to this method to launch a new activity or get an existing activity to do something new. 2 Context.startService() The Intent object is passed to this method to initiate a service or deliver new instructions to an ongoing service. 3 Context.sendBroadcast() The Intent object is passed to this method to deliver the message to all interested broadcast receivers. Intent Objects An Intent object is a bundle of information which is used by the component that receives the intent as well as information used by the Android system. An Intent object can contain the following components based on what it is communicating or going to perform − Action This is mandatory part of the Intent object and is a string naming the action to be performed — or, in the case of broadcast intents, the action that took place and is being reported. The action largely determines how the rest of the intent object is structured . The Intent class defines a number of action constants corresponding to different intents. Here is a list of Android Intent Standard Actions The action in an Intent object can be set by the setAction() method and read by getAction(). Data Adds a data specification to an intent filter. The specification can be just a data type (the mimeType attribute), just a URI, or both a data type and a URI. A URI is specified by separate attributes for each of its parts − These attributes that specify the URL format are optional, but also mutually dependent − If a scheme is not specified for the intent filter, all the other URI attributes are ignored. If a host is not specified for the filter, the port attribute and all the path attributes are ignored. The setData() method specifies data only as a URI, setType() specifies it only as a MIME type, and setDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData() and the type by getType(). Some examples of action/data pairs are − Sr.No. Action/Data Pair & Description 1 ACTION_VIEW content://contacts/people/1 Display information about the person whose identifier is “1”. 2 ACTION_DIAL content://contacts/people/1 Display the phone dialer with the person filled in. 3 ACTION_VIEW tel:123 Display the phone dialer with the given number filled in. 4 ACTION_DIAL tel:123 Display the phone dialer with the given number filled in. 5 ACTION_EDIT content://contacts/people/1 Edit information about the person whose identifier is “1”. 6 ACTION_VIEW content://contacts/people/ Display a list of people, which the user can browse through. 7 ACTION_SET_WALLPAPER Show settings for choosing wallpaper 8 ACTION_SYNC It going to be synchronous the data,Constant Value is android.intent.action.SYNC 9 ACTION_SYSTEM_TUTORIAL It will start the platform-defined tutorial(Default tutorial or start up tutorial) 10 ACTION_TIMEZONE_CHANGED It intimates when time zone has changed 11 ACTION_UNINSTALL_PACKAGE It is used to run default uninstaller Category The category is an optional part of Intent object and it”s a string containing additional information about the kind of component that should handle the intent. The addCategory() method places a category in an Intent object, removeCategory() deletes a category previously added, and getCategories() gets the set of all categories currently in the object. Here is a list of Android Intent Standard Categories. You can check detail on Intent Filters in below section to understand how do we use categories to choose appropriate activity corresponding to an Intent. Extras This will be in key-value pairs for additional information that should be delivered to the component handling the intent. The extras can be set and read using the putExtras() and getExtras() methods respectively. Here is a list of Android Intent Standard Extra Data Flags These flags are optional part of Intent object and instruct the Android system how to launch an activity, and how to treat it after it”s launched etc. Sr.No Flags & Description 1 FLAG_ACTIVITY_CLEAR_TASK If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty

Android – Fragments

Android – Fragments ”; Previous Next A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-activity. Following are important points about fragment − A fragment has its own layout and its own behaviour with its own life cycle callbacks. You can add or remove fragments in an activity while the activity is running. You can combine multiple fragments in a single activity to build a multi-pane UI. A fragment can be used in multiple activities. Fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused, all the fragments available in the activity will also be stopped. A fragment can implement a behaviour that has no user interface component. Fragments were added to the Android API in Honeycomb version of Android which API version 11. You create fragments by extending Fragment class and You can insert a fragment into your activity layout by declaring the fragment in the activity”s layout file, as a <fragment> element. Prior to fragment introduction, we had a limitation because we can show only a single activity on the screen at one given point in time. So we were not able to divide device screen and control different parts separately. But with the introduction of fragment we got more flexibility and removed the limitation of having a single activity on the screen at a time. Now we can have a single activity but each activity can comprise of multiple fragments which will have their own layout, events and complete life cycle. Following is a typical example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design. The application can embed two fragments in Activity A, when running on a tablet-sized device. However, on a handset-sized screen, there”s not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment to read the article. Fragment Life Cycle Android fragments have their own life cycle very similar to an android activity. This section briefs different stages of its life cycle. Fragment lifecycle Here is the list of methods which you can to override in your fragment class − onAttach()The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work. onCreate() The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed. onCreateView() The system calls this callback when it”s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment”s layout. You can return null if the fragment does not provide a UI. onActivityCreated()The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object onStart()The onStart() method is called once the fragment gets visible. onResume()Fragment becomes active. onPause() The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session. onStop()Fragment going to be stopped by calling onStop() onDestroyView()Fragment view will destroy after call this method onDestroy()onDestroy() called to do final clean up of the fragment”s state but Not guaranteed to be called by the Android platform. How to use Fragments? This involves number of simple steps to create Fragments. First of all decide how many fragments you want to use in an activity. For example let”s we want to use two fragments to handle landscape and portrait modes of the device. Next based on number of fragments, create classes which will extend the Fragment class. The Fragment class has above mentioned callback functions. You can override any of the functions based on your requirements. Corresponding to each fragment, you will need to create layout files in XML file. These files will have layout for the defined fragments. Finally modify activity file to define the actual logic of replacing fragments based on your requirement. Types of Fragments Basically fragments are divided as three stages as shown below. Single frame fragments − Single frame fragments are using for hand hold devices like mobiles, here we can show only one fragment as a view. List fragments − fragments having special list view is called as list fragment Fragments transaction − Using with fragment transaction. we can move one fragment to another fragment. Print Page Previous Next Advertisements ”;

Android – Architecture

Android – Architecture ”; Previous Next Android operating system is a stack of software components which is roughly divided into five sections and four main layers as shown below in the architecture diagram. Linux kernel At the bottom of the layers is Linux – Linux 3.6 with approximately 115 patches. This provides a level of abstraction between the device hardware and it contains all the essential hardware drivers like camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good at such as networking and a vast array of device drivers, which take the pain out of interfacing to peripheral hardware. Libraries On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit, well known library libc, SQLite database which is a useful repository for storage and sharing of application data, libraries to play and record audio and video, SSL libraries responsible for Internet security etc. Android Libraries This category encompasses those Java-based libraries that are specific to Android development. Examples of libraries in this category include the application framework libraries in addition to those that facilitate user interface building, graphics drawing and database access. A summary of some key core Android libraries available to the Android developer is as follows − android.app − Provides access to the application model and is the cornerstone of all Android applications. android.content − Facilitates content access, publishing and messaging between applications and application components. android.database − Used to access data published by content providers and includes SQLite database management classes. android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API. android.os − Provides applications with access to standard operating system services including messages, system services and inter-process communication. android.text − Used to render and manipulate text on a device display. android.view − The fundamental building blocks of application user interfaces. android.widget − A rich collection of pre-built user interface components such as buttons, labels, list views, layout managers, radio buttons etc. android.webkit − A set of classes intended to allow web-browsing capabilities to be built into applications. Having covered the Java-based core libraries in the Android runtime, it is now time to turn our attention to the C/C++ based libraries contained in this layer of the Android software stack. Android Runtime This is the third section of the architecture and available on the second layer from the bottom. This section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially designed and optimized for Android. The Dalvik VM makes use of Linux core features like memory management and multi-threading, which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine. The Android runtime also provides a set of core libraries which enable Android application developers to write Android applications using standard Java programming language. Application Framework The Application Framework layer provides many higher-level services to applications in the form of Java classes. Application developers are allowed to make use of these services in their applications. The Android framework includes the following key services − Activity Manager − Controls all aspects of the application lifecycle and activity stack. Content Providers − Allows applications to publish and share data with other applications. Resource Manager − Provides access to non-code embedded resources such as strings, color settings and user interface layouts. Notifications Manager − Allows applications to display alerts and notifications to the user. View System − An extensible set of views used to create application user interfaces. Applications You will find all the Android application at the top layer. You will write your application to be installed on this layer only. Examples of such applications are Contacts Books, Browser, Games etc. Print Page Previous Next Advertisements ”;

Android – Hello World Example

Android – Hello World Example ”; Previous Next Let us start actual programming with Android Framework. Before you start writing your first example using Android SDK, you have to make sure that you have set-up your Android development environment properly as explained in Android – Environment Set-up tutorial. I also assume that you have a little bit working knowledge with Android studio. So let us proceed to write a simple Android Application which will print “Hello World!”. Create Android Application The first step is to create a simple Android Application using Android studio. When you click on Android studio icon, it will show screen as shown below You can start your application development by calling start a new android studio project. in a new installation frame should ask Application name, package information and location of the project.− After entered application name, it going to be called select the form factors your application runs on, here need to specify Minimum SDK, in our tutorial, I have declared as API23: Android 6.0(Mashmallow) − The next level of installation should contain selecting the activity to mobile, it specifies the default layout for Applications. At the final stage it going to be open development tool to write the application code. Anatomy of Android Application Before you run your app, you should be aware of a few directories and files in the Android project − Sr.No. Folder, File & Description 1 Java This contains the .java source files for your project. By default, it includes an MainActivity.java source file having an activity class that runs when your app is launched using the app icon. 2 res/drawable-hdpi This is a directory for drawable objects that are designed for high-density screens. 3 res/layout This is a directory for files that define your app”s user interface. 4 res/values This is a directory for other various XML files that contain a collection of resources, such as strings and colours definitions. 5 AndroidManifest.xml This is the manifest file which describes the fundamental characteristics of the app and defines each of its components. 6 Build.gradle This is an auto generated file which contains compileSdkVersion, buildToolsVersion, applicationId, minSdkVersion, targetSdkVersion, versionCode and versionName Following section will give a brief overview of the important application files. The Main Activity File The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World! application − package com.example.helloworld; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. The onCreate() method is one of many methods that are figured when an activity is loaded. The Manifest File Whatever component you develop as a part of your application, you must declare all its components in a manifest.xml which resides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file − <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.tutorialspoint7.myapplication”> <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”> <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Here <application>…</application> tags enclosed the components related to the application. Attribute android:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify multiple activities using <activity> tags. The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the application. The category for the intent-filter is named android.intent.category.LAUNCHER to indicate that the application can be launched from the device”s launcher icon. The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to the app_name string defined in the strings.xml file, which is “HelloWorld”. Similar way, other strings get populated in the application. Following is the list of tags which you will use in your manifest file to specify different Android application components − <activity>elements for activities <service> elements for services <receiver> elements for broadcast receivers <provider> elements for content providers The Strings File The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. For example, a default strings file will look like as following file − <resources> <string name=”app_name”>HelloWorld</string> <string name=”hello_world”>Hello world!</string> <string name=”menu_settings”>Settings</string> <string name=”title_activity_main”>MainActivity</string> </resources> The Layout File The activity_main.xml is a layout file available in res/layout directory, that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application. For your “Hello World!” application, this file will have following content related to default layout − <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” > <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_centerHorizontal=”true” android:layout_centerVertical=”true” android:padding=”@dimen/padding_medium” android:text=”@string/hello_world” tools:context=”.MainActivity” /> </RelativeLayout> This is an example of simple RelativeLayout which we will study in a separate chapter. The TextView is an Android control used to build the GUI and it have various attributes like android:layout_width, android:layout_height etc which are being used to set its width and height etc.. The @string refers to the strings.xml file located in the res/values folder. Hence, @string/hello_world refers to the hello string defined in the strings.xml file, which is “Hello World!”. Running the Application Let”s try to run our Hello World! application we just created. I assume you had created

Android – Services

Android – Services ”; Previous Next A service is a component that runs in the background to perform long-running operations without needing to interact with the user and it works even if application is destroyed. A service can essentially take two states − Sr.No. State & Description 1 Started A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. 2 Bound A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A service has life cycle callback methods that you can implement to monitor changes in the service”s state and you can perform work at the appropriate stage. The following diagram on the left shows the life cycle when the service is created with startService() and the diagram on the right shows the life cycle when the service is created with bindService(): (image courtesy : android.com ) To create an service, you create a Java class that extends the Service base class or one of its existing subclasses. The Service base class defines various callback methods and the most important are given below. You don”t need to implement all the callbacks methods. However, it”s important that you understand each one and implement those that ensure your app behaves the way users expect. Sr.No. Callback & Description 1 onStartCommand() The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). If you implement this method, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService() methods. 2 onBind() The system calls this method when another component wants to bind with the service by calling bindService(). If you implement this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder object. You must always implement this method, but if you don”t want to allow binding, then you should return null. 3 onUnbind() The system calls this method when all clients have disconnected from a particular interface published by the service. 4 onRebind() The system calls this method when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent). 5 onCreate() The system calls this method when the service is first created using onStartCommand() or onBind(). This call is required to perform one-time set-up. 6 onDestroy() The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. The following skeleton service demonstrates each of the life cycle methods − package com.tutorialspoint; import android.app.Service; import android.os.IBinder; import android.content.Intent; import android.os.Bundle; public class HelloService extends Service { /** indicates how to behave if the service is killed */ int mStartMode; /** interface for clients that bind */ IBinder mBinder; /** indicates whether onRebind should be used */ boolean mAllowRebind; /** Called when the service is being created. */ @Override public void onCreate() { } /** The service is starting, due to a call to startService() */ @Override public int onStartCommand(Intent intent, int flags, int startId) { return mStartMode; } /** A client is binding to the service with bindService() */ @Override public IBinder onBind(Intent intent) { return mBinder; } /** Called when all clients have unbound with unbindService() */ @Override public boolean onUnbind(Intent intent) { return mAllowRebind; } /** Called when a client is binding to the service with bindService()*/ @Override public void onRebind(Intent intent) { } /** Called when The service is no longer used and is being destroyed */ @Override public void onDestroy() { } } Example This example will take you through simple steps to show how to create your own Android Service. Follow the following steps to modify the Android application we created in Hello World Example chapter − Step Description 1 You will use Android StudioIDE to create an Android application and name it as My Application under a package com.example.tutorialspoint7.myapplication as explained in the Hello World Example chapter. 2 Modify main activity file MainActivity.java to add startService() and stopService() methods. 3 Create a new java file MyService.java under the package com.example.My Application. This file will have implementation of Android service related methods. 4 Define your service in AndroidManifest.xml file using <service…/> tag. An application can have one or more services without any restrictions. 5 Modify the default content of res/layout/activity_main.xml file to include two buttons in linear layout. 6 No need to change any constants in res/values/strings.xml file. Android studio take care of string values 7 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity file MainActivity.java. This file can include each of the fundamental life cycle methods. We have added startService() and stopService() methods to start and stop the service. package com.example.tutorialspoint7.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.View; public class MainActivity extends Activity { String msg = “Android : “; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(msg, “The onCreate() event”); } public void startService(View view) { startService(new Intent(getBaseContext(), MyService.class)); } // Method to stop the service public void stopService(View view) { stopService(new Intent(getBaseContext(), MyService.class)); } } Following is the content of MyService.java. This file can have implementation of one or more methods associated with Service based on requirements. For now we are going to implement only two methods onStartCommand() and onDestroy() − package com.example.tutorialspoint7.myapplication; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.widget.Toast; /** * Created by TutorialsPoint7 on