Android Interview Questions?

What is android?

Android is a stack of software for mobile devices which has Operating System, middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine. Many Virtual Machines run efficiently by a DVM device. DVM executes Java language’s byte code which later transforms into .dex format files.

Why to use Android?

Android is useful because:
  • It is simple and powerful SDK
  • Licensing, Distribution or Development fee is not required
  • Easy to Import third party Java library
  • Supporting platforms are – Linux, Mac Os, Windows

Describe Android Application Architecture.

Android Application Architecture has the following components:
  • Services – like Network Operation
  • Intent - To perform inter-communication between activities or services
  • Resource Externalization - such as strings and graphics
  • Notification signaling users - light, sound, icon, notification, dialog etc.
  • Content Providers - They share data between applications

Describe a real time scenario where android can be used

Imagine a situation that you are in a country where no one understands the language you speak and you can not read or write. However, you have mobile phone with you.
With a mobile phone with android, the Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.

What are the advantages of Android?

The following are the advantages of Android:
  • The customer will be benefited from wide range of mobile applications to choose, since the monopoly of wireless carriers like AT&T and Orange will be broken by Google Android.
  • Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized
  • Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in Android.

How to select more than one option from list in android xml file? Give an example.

Specify android id, layout height and width as depicted in the following example.
<ListView android:id="@+id/ListView01" android:layout_height="wrap_content" android:layout_width="fill_parent"></ListView>

What is needed to make a multiple choice list with a custom view for each row?

Multiple choice list can be viewed by making the CheckBox android:id value be “@android:id /text1". That is the ID used by Android for the CheckedTextView in simple_list_item_multiple_choice.

What are the dialog boxes that are supported in android? Explain.

Android supports 4 dialog boxes:
AlertDialog : An alert dialog box supports 0 to 3 buttons and a list of selectable elements, including check boxes and radio buttons. Among the other dialog boxes, the most suggested dialog box is the alert dialog box.
ProgressDialog: This dialog box displays a progress wheel or a progress bar. It is an extension of AlertDialog and supports adding buttons.
DatePickerDialog: This dialog box is used for selecting a date by the user.
TimePickerDialog: This dialog box is used for selecting time by the user.

Explain about the exceptions of Android.

The following are the exceptions that are supported by Android
  • InflateException : When an error conditions are occurred, this exception is thrown
  • Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown
  • SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS
  • WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.

What is the TTL (Time to Live)? Why is it required?

TTL is a value in data packet of Internet Protocol. It communicates to the network router whether or not the packet should be in the network for too long or discarded. Usually, data packets might not be transmitted to their intended destination within a stipulated period of time. The TTL value is set by a system default value which is an 8-bit binary digit field in the header of the packet. The purpose of TTL is, it would specify certain time limit in seconds, for transmitting the packet header. When the time is exhausted, the packet would be discarded. Each router receives the subtracts count, when the packet is discarded, and when it becomes zero, the router detects the discarded packets and sends a message, Internet Control Message Protocol message back to the originating host.

What are the differences between a domain and a workgroup?

In a domain, one or more computer can be a server to manage the network. On the other hand in a workgroup all computers are peers having no control on each other. In a domain, user doesn’t need an account to logon on a specific computer if an account is available on the domain. In a work group user needs to have an account for every computer.
In a domain, Computers can be on different local networks. In a work group all computers needs to be a part of the same local network.
What is the future scope of Mobile Application developers?
Answer : There’s a huge demand for mobile applications now, with the mobile devices evolving to a state that you can actually do stuff (mostly bigger display and higher processing power). It is not a market that is mature now, so there are a lot of opportunities – explaining the big number of players joining the game.
As the market matures, big players are going to stand out, making the competition tougher, so I think it’s save to say the single players will have a harder time competing.
What is Android Runtime?
Answer : Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included “dx” tool.
The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.
What are the features of Android?
Answer : Android OS 2.0 features :
The most interesting feature of Android OS 2.0 is the free Google maps navigation in selected areas .Android 2.0 supports Bluetooth version 2.1.
New Android global search function that can search the phone for everything from SMS, MMS, email messages, web, contacts etc. to calender entries.
Native webkit browser will support support HTML 5 and other new web standards.
Multiple screen resolutions possible.
Excellent text-to speech API on which we can expect good applications.

Top 50 Interview Questions:
1) What is Android?
It is an open-sourced operating system that is used primarily on mobile devices, such as cell phones and tablets. It is a Linux kernel-based system that’s been equipped with rich components that allows developers to create and run apps that can perform both basic and advanced functions.
2) What Is the Google Android SDK?
The Google Android SDK is a toolset that developers need in order to write apps on Android enabled devices. It contains a graphical interface that emulates an Android driven handheld environment, allowing them to test and debug their codes.
3) What is the Android Architecture?
Android Architecture is made up of 4 key components:
- Linux Kernel
- Libraries
- Android Framework
- Android Applications

4) Describe the Android Framework.
The Android Framework is an important aspect of the Android Architecture. Here you can find all the classes and methods that developers would need in order to write applications on the Android environment.
5) What is AAPT?
AAPT is short for Android Asset Packaging Tool. This tool provides developers with the ability to deal with zip-compatible archives, which includes creating, extracting as well as viewing its contents.
6) What is the importance of having an emulator within the Android environment?
The emulator lets developers “play” around an interface that acts as if it were an actual mobile device. They can write and test codes, and even debug. Emulators are a safe place for testing codes especially if it is in the early design phase.
7) What is the use of an activityCreator?
An activityCreator is the first step towards the creation of a new Android project. It is made up of a shell script that will be used to create new file system structure necessary for writing codes within the Android IDE.
8 ) Describe Activities.
Activities are what you refer to as the window to a user interface. Just as you create windows in order to display output or to ask for an input in the form of dialog boxes, activities play the same role, though it may not always be in the form of a user interface.
9) What are Intents?
Intents displays notification messages to the user from within the Android enabled device. It can be used to alert the user of a particular state that occurred. Users can be made to respond to intents.
10) Differentiate Activities from Services.
Activities can be closed, or terminated anytime the user wishes. On the other hand, services are designed to run behind the scenes, and can act independently. Most services run continuously, regardless of whether there are certain or no activities being executed.
11) What items are important in every Android project?
These are the essential items that are present each time an Android project is created:
- AndroidManifest.xml
- build.xml
- bin/
- src/
- res/
- assets/

12) What is the importance of XML-based layouts?
The use of XML-based layouts provides a consistent and somewhat standard means of setting GUI definition format. In common practice, layout details are placed in XML files while other items are placed in source files.
13) What are containers?
Containers, as the name itself implies, holds objects and widgets together, depending on which specific items are needed and in what particular arrangement that is wanted. Containers may hold labels, fields, buttons, or even child containers, as examples.
14) What is Orientation?
Orientation, which can be set using setOrientation(), dictates if the LinearLayout is represented as a row or as a column. Values are set as either HORIZONTAL or VERTICAL.
15) What is the importance of Android in the mobile market?
Developers can write and register apps that will specifically run under the Android environment. This means that every mobile device that is Android enabled will be able to support and run these apps. With the growing popularity of Android mobile devices, developers can take advantage of this trend by creating and uploading their apps on the Android Market for distribution to anyone who wants to download it.
16) What do you think are some disadvantages of Android?
Given that Android is an open-source platform, and the fact that different Android operating systems have been released on different mobile devices, there’s no clear cut policy to how applications can adapt with various OS versions and upgrades. One app that runs on this particular version of Android OS may or may not run on another version. Another disadvantage is that since mobile devices such as phones and tabs come in different sizes and forms, it poses a challenge for developers to create apps that can adjust correctly to the right screen size and other varying features and specs.
17) What is adb?
Adb is short for Android Debug Bridge. It allows developers the power to execute remote shell commands. Its basic function is to allow and control communication towards and from the emulator port.
18) What are the four essential states of an activity?
- Active – if the activity is at the foreground
- Paused – if the activity is at the background and still visible
- Stopped – if the activity is not visible and therefore is hidden or obscured by another activity
- Destroyed – when the activity process is killed or completed terminated

19) What is ANR?
ANR is short for Application Not Responding. This is actually a dialog that appears to the user whenever an application have been unresponsive for a long period of time.
20) Which elements can occur only once and must be present?
Among the different elements, the and elements must be present and can occur only once. The rest are optional, and can occur as many times as needed.
21) How are escape characters used as attribute?
Escape characters are preceded by double backslashes. For example, a newline character is created using ‘\\n’
22) What is the importance of settings permissions in app development?
Permissions allow certain restrictions to be imposed primarily to protect data and code. Without these, codes could be compromised, resulting to defects in functionality.
23) What is the function of an intent filter?
Because every component needs to indicate which intents they can respond to, intent filters are used to filter out intents that these components are willing to receive. One or more intent filters are possible, depending on the services and activities that is going to make use of it.
24) Enumerate the three key loops when monitoring an activity
- Entire lifetime – activity happens between onCreate and onDestroy
- Visible lifetime – activity happens between onStart and onStop
- Foreground lifetime – activity happens between onResume and onPause

25) When is the onStop() method invoked?
A call to onStop method happens when an activity is no longer visible to the user, either because another activity has taken over or if in front of that activity.
26) Is there a case wherein other qualifiers in multiple resources take precedence over locale?
Yes, there are actually instances wherein some qualifiers can take precedence over locale. There are two known exceptions, which are the MCC (mobile country code) and MNC (mobile network code) qualifiers.
27) What are the different states wherein a process is based?
There are 4 possible states:
- foreground activity
- visible activity
- background activity
- empty process

28) How can the ANR be prevented?
One technique that prevents the Android system from concluding a code that has been responsive for a long period of time is to create a child thread. Within the child thread, most of the actual workings of the codes can be placed, so that the main thread runs with minimal periods of unresponsive times.
29) What role does Dalvik play in Android development?
Dalvik serves as a virtual machine, and it is where every Android application runs. Through Dalvik, a device is able to execute multiple virtual machines efficiently through better memory management.
30) What is the AndroidManifest.xml?
This file is essential in every application. It is declared in the root directory and contains information about the application that the Android system must know before the codes can be executed.
31) What is the proper way of setting up an Android-powered device for app development?
The following are steps to be followed prior to actual application development in an Android-powered device:
-Declare your application as “debuggable” in your Android Manifest.
-Turn on “USB Debugging” on your device.
-Set up your system to detect your device.

32) Enumerate the steps in creating a bounded service through AIDL.
1. create the .aidl file, which defines the programming interface
2. implement the interface, which involves extending the inner abstract Stub class as well as implanting its methods.
3. expose the interface, which involves implementing the service to the clients.

33) What is the importance of Default Resources?
When default resources, which contain default strings and files, are not present, an error will occur and the app will not run. Resources are placed in specially named subdirectories under the project res/ directory.
34) When dealing with multiple resources, which one takes precedence?
Assuming that all of these multiple resources are able to match the configuration of a device, the ‘locale’ qualifier almost always takes the highest precedence over the others.
35) When does ANR occur?
The ANR dialog is displayed to the user based on two possible conditions. One is when there is no response to an input event within 5 seconds, and the other is when a broadcast receiver is not done executing within 10 seconds.
36) What is AIDL?
AIDL, or Android Interface Definition Language, handles the interface requirements between a client and a service so both can communicate at the same level through interprocess communication or IPC. This process involves breaking down objects into primitives that Android can understand. This part is required simply because a process cannot access the memory of the other process.
37) What data types are supported by AIDL?
AIDL has support for the following data types:
-string
-charSequence
-List
-Map
-all native Java data types like int,long, char and Boolean

38) What is a Fragment?
A fragment is a part or portion of an activity. It is modular in a sense that you can move around or combine with other fragments in a single activity. Fragments are also reusable.
39) What is a visible activity?
A visible activity is one that sits behind a foreground dialog. It is actually visible to the user, but not necessarily being in the foreground itself.
40) When is the best time to kill a foreground activity?
The foreground activity, being the most important among the other states, is only killed or terminated as a last resort, especially if it is already consuming too much memory. When a memory paging state has been reach by a foreground activity, then it is killed so that the user interface can retain its responsiveness to the user.
41) Is it possible to use or add a fragment without using a user interface?
Yes, it is possible to do that, such as when you want to create a background behavior for a particular activity. You can do this by using add(Fragment,string) method to add a fragment from the activity.
42) How do you remove icons and widgets from the main screen of the Android device?
To remove an icon or shortcut, press and hold that icon. You then drag it downwards to the lower part of the screen where a remove button appears.
43) What are the core components under the Android application architecture?
There are 5 key components under the Android application architecture:
- services
- intent
- resource externalization
- notifications
- content providers

44) What composes a typical Android application project?
A project under Android development, upon compilation, becomes an .apk file. This apk file format is actually made up of the AndroidManifest.xml file, application code, resource files, and other related files.
45) What is a Sticky Intent?
A Sticky Intent is a broadcast from sendStickyBroadcast() method such that the intent floats around even after the broadcast, allowing others to collect data from it.
46) Do all mobile phones support the latest Android operating system?
Some Android-powered phone allows you to upgrade to the higher Android operating system version. However, not all upgrades would allow you to get the latest version. It depends largely on the capability and specs of the phone, whether it can support the newer features available under the latest Android version.
47) What is portable wi-fi hotspot?
Portable Wi-Fi Hotspot allows you to share your mobile internet connection to other wireless device. For example, using your Android-powered phone as a Wi-Fi Hotspot, you can use your laptop to connect to the Internet using that access point.
48) What is an action?
In Android development, an action is what the intent sender wants to do or expected to get as a response. Most application functionality is based on the intended action.
49) What is the difference between a regular bitmap and a nine-patch image?
In general, a Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.
50) What language is supported by Android for application development?
The main language supported is Java programming language. Java is the most popular language for app development, which makes it ideal even for new Android developers to quickly learn to create and deploy applications in the Android environment.

Frequently Asked Questions:
  • Explain the life cycle of an application development process you worked on previously.
  • What the interviewer looks for is communication of requirements, planning, modeling, construction and deployment on the back end.
  • Here's a hypothetical project. Explain how you would go about it.
  • How do you respond to requirement changes in the middle of a cycle?
  • What type of methodology have you used in the past? What are its drawbacks?
  • What are different techniques for prototyping an application?
  • How do you manage conflicts in Web applications when there are different people managing data?
  • Tell me something you learned from a team member in the last year.
  • What software testing procedures have you used to perform a QA?
  • ·The Activity life cycle is must. Ask about the different phases of Activity Life cycle. For example: when and how the activity comes to foreground?
  • ·Check the knowledge on AndroidManifest file, For example: Why do we need this file, What is the role of this file in Android app development.
  • ·Different Kinds of Intents
  • ·Ask about different Kinds of context
  • · Ask about different Storage Methods in android
  • ·Kinds of Log debugger and Debugger Configuration
  • ·How to debug the application on real device.
  • ·How do you ensure that the app design will be consistent across the different screen resolutions
  • ·Thread concepts also plus points as we deal with the treads more.
  • ·Can you able to build custom views and how?
  • ·How to create flexible layouts, For example to place English, Chinese fonts.
  • · What is localization and how to achieve?
  • ·What are 9-patch images
  • ·How to avoid ANR status
  • ·How to do Memory management
  • ·Ask about IPC
  • ·What is onCreate(Bundle savedInstanceState), Have you used savedInstanceState when and why?
  • ·To check how updated the person is just ask about what are Fragments in an Activity
  • Application lifecycle
  • When to use a service
  • How to use a broadcast receiver and register it both in the manifest and in code
  • Intent filters
  • Stuff about what manifest attributes and tags mean
  • The types of flags to run an application
    FLAG_ACTIVITY_NEW_TASK
    FLAG_ACTIVITY_CLEAR_TOP
  • How to do data intensive calculations using threads
  • Passing large objects (that can't be passed via intents and shouldn't be serialized) via a service
  • Binding to a service and the service lifecycle
  • How to persist data (both savedInstanceState and more permanent ways)

Android Count Down Timer Examples?

Here another nice topic am cover Countdown Timer , Here Is the Android Official Documentation is http://developer.android.com/reference/android/os/CountDownTimer.html ,

In this topic am fount two types of  count down timers.

FIRST ONE:


  1.   String oldFormat = "yyyy-MM-dd HH:mm:ss";

       SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
       TimeZone obj = TimeZone.getTimeZone("CST");
           sdf1.setTimeZone(obj);
         
           Date date = sdf1.parse(" your match time ");
           millis = date.getTime();


          long currentTimeInMili = new Date().getTime(); // Current time
          final CountDownTimer Counter1 = new CountDownTimer(millis - currentTimeInMili, 1 * 1000) {
             public void onTick(long millisUntilFinished) {
                  matchUpcomingText.setText("" + formatTime(millisUntilFinished) + "till match start");
        }

        public void onFinish() {
       matchUpcomingText.setText("Finished!");
           }
         }.start();

SECOND ONE:


  1. String oldFormat = "yyyy-MM-dd HH:mm:ss";

       SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
       TimeZone obj = TimeZone.getTimeZone("CST");
           sdf1.setTimeZone(obj);
         
           Date date = sdf1.parse(" your match time ");
           millis = date.getTime();

    long currentTimeInMili = new Date().getTime();
    MyCount counter = new MyCount(millis - currentTimeInMili, 1 * 1000);
    counter.start();

        public static class MyCount extends CountDownTimer {
    public MyCount(long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    }// MyCount
    public void onPause() {
    onPause();
    }// finish
    public void onTick(long millisUntilFinished) {
    matchUpcomingText.setText(""+ formatTime(millisUntilFinished)+ " till match start");
    Log.i(" formatTime ==> ", "" + formatTime(millisUntilFinished));
    Log.i(" millisUntilFinished ==> ", "" + millisUntilFinished);
    }// on tick
    @Override
    public void onFinish() {
    //onStop();
    }// finish
    }

    public static String formatTime(long millis) {
    String output = "00:00";
    try {
    long seconds = millis / 1000;
    long minutes = seconds / 60;
    long hours = seconds / 3600;
    long days = seconds / (3600 * 24);

    seconds = seconds % 60;
    minutes = minutes % 60;
    hours = hours % 24;
    days = days % 30;

    String sec = String.valueOf(seconds);
    String min = String.valueOf(minutes);
    String hur = String.valueOf(hours);
    String day = String.valueOf(days);

    if (seconds < 10)
    sec = "0" + seconds;
    if (minutes < 10)
    min = "0" + minutes;
    if (hours < 10)
    hur = "0" + hours;
    if (days < 10)
    day = "0" + days;

    output = day + "D " + hur + "H " + min + "M " + sec + "S";
    } catch (Exception e) {
    e.printStackTrace();
    }
    return output;
    } 
   

Audio file Save to SdCard and play using MediaPlayer?

 Android has a built in microphone through which you can capture audio and store it , or play it in your phone. There are many ways to do that but the most common way is through MediaRecorder class.
Android provides MediaRecorder class to record audio or video. In order to use MediaRecorder class ,you will first create an instance of MediaRecorder class. Its syntax is given below.
MediaRecorder myAudioRecorder = new MediaRecorder();
Now you will set the source , output and encoding format and output file. Their syntax is given below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
After specifying the audio source and format and its output file, we can then call the two basic methods perpare and start to start recording the audio.
myAudioRecorder.prepare();
myAudioRecorder.start();
Apart from these methods , there are other methods listed in the MediaRecorder class that allows you more control over audio and video recording.
Sr.NoMethod & description
1setAudioSource()
This method specifies the source of audio to be recorded
2setVideoSource()
This method specifies the source of video to be recorded
3setOutputFormat()
This method specifies the audio format in which audio to be stored
4setAudioEncoder()
This method specifies the audio encoder to be used
5setOutputFile()
This method configures the path to the file into which the recorded audio is to be stored
6stop()
This method stops the recording process.
7release()
This method should be called when the recorder instance is needed.

Example

 Create MainActivity.java


  1.   public class MainActivity extends Activity {

    private MediaRecorder myAudioRecorder;
    private String outputFile = null;
    private Button start, stop, play, pause;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    start = (Button) findViewById(R.id.button1);
    stop = (Button) findViewById(R.id.button2);
    play = (Button) findViewById(R.id.button3);
    pause = (Button) findViewById(R.id.button4);

    stop.setEnabled(false);
    play.setEnabled(false);
    pause.setEnabled(false)
    ; outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myrecording.3gp";  

    myAudioRecorder = new MediaRecorder();
    myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
    myAudioRecorder.setOutputFile(outputFile);
    }

    public void start(View view) {
    try {
    myAudioRecorder.prepare();
    myAudioRecorder.start();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    start.setEnabled(false);
    stop.setEnabled(true);
    pause.setEnabled(false);
    Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();

    }

    public void stop(View view) {
    myAudioRecorder.stop();
    myAudioRecorder.release();
    myAudioRecorder = null;
    stop.setEnabled(false);
    play.setEnabled(true);
    Toast.makeText(getApplicationContext(), "Audio recorded successfully", Toast.LENGTH_LONG).show();
    }
    public void pause(View view) throws IllegalArgumentException,
    SecurityException, IllegalStateException, IOException  {
    MediaPlayer media = new MediaPlayer();
    media.setDataSource(outputFile);
    media.prepare();
    media.pause();
    Toast.makeText(getApplicationContext(), "Audio pause ", Toast.LENGTH_LONG).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.main, menu);
    return true;
    }

    public void play(View view) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {

    MediaPlayer media = new MediaPlayer();
    if (media.isPlaying()) {
    media.setDataSource(outputFile);
         media.prepare();
      media.pause();
            } else {
             media.setDataSource(outputFile);
         media.prepare();
         media.start();         
            }  
    pause.setEnabled(true);
    Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
    }
    }

main.xml

  1.   <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"
        tools:context=".MainActivity" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="32dp"
            android:text="Recording"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_below="@+id/textView1"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="37dp"
            android:scaleType="fitXY"
            android:src="@android:drawable/presence_audio_online" />

        <LinearLayout
            android:id="@+id/linear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/imageView1"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/imageView1"
                android:layout_toLeftOf="@+id/imageView1"
                android:onClick="start"
                android:text="start" />

            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/button1"
                android:layout_alignBottom="@+id/button1"
                android:layout_alignRight="@+id/textView1"
                android:onClick="stop"
                android:text="stop" />

            <Button
                android:id="@+id/button3"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/button2"
                android:onClick="play"
                android:text="play" />

            <Button
                android:id="@+id/button4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/button2"
                android:layout_alignRight="@+id/textView1"
                android:onClick="pause"
                android:text="pause" />
        </LinearLayout>

    </RelativeLayout>

Send Data to Gmail useing Android Application?


Following section explains different parts of our Intent object required to send an email.

Intent Object - Action to send Email

You will use ACTION_SEND action to launch an email client installed on your Android device. Following is simple syntax to create an intent with ACTION_SEND action
Intent emailIntent = new Intent(Intent.ACTION_SEND);

Intent Object - Data/Type to send Email

To send an email you need to specify mailto: as URI using setData() method and data type will be totext/plain using setType() method as follows:
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");

Intent Object - Extra to send Email

Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be attached to the intent before sending the intent to a target email client. You can use following extra fields in your email:
S.N.Extra Data & Description
1EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.
2EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.
3EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.
4EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND to supply an alternative to EXTRA_TEXT as HTML formatted text.
5EXTRA_SUBJECT
A constant string holding the desired subject line of a message.
6EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with ACTION_SEND to supply the literal data to be sent.
7EXTRA_TITLE
A CharSequence dialog title to provide to the user when used with a ACTION_CHOOSER.
Here is an example showing you how to assign extra data to your intent:
emailIntent.putExtra(Intent.EXTRA_EMAIL  , new String[]{"recipient@example.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
emailIntent.putExtra(Intent.EXTRA_TEXT   , "body of email");

Example


MainActivity.java

  1.  public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_EMAIL,new String[] { "" });
    i.putExtra(Intent.EXTRA_SUBJECT," \n\n www.google.com"); // your url
    i.putExtra(Intent.EXTRA_TEXT,"new test"); // your text in place of contentStr
    try {
    MainActivity.this.startActivity(Intent.createChooser(i,"Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
    ex.printStackTrace();
    }
    }
    });
    }

    }

main.xml

  1.  <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"
        tools:context=".MainActivity" >

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView1"
            android:layout_below="@+id/textView1"
            android:text="Send data to gmail" />

    </RelativeLayout>

Android Application Components?

Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact.
There are following four main components that can be used within an Android application:
ComponentsDescription
ActivitiesThey they dictate the UI and handle the user interaction to the smartphone screen
ServicesThey handle background processing associated with an application.
Broadcast ReceiversThey handle communication between Android OS and applications.
Content ProvidersThey handle data and database management issues.

Activities

An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows:
public class MainActivity extends Activity {

}

Services

A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.
A service is implemented as a subclass of Service class as follows:
public class MyService extends Service {

}

Broadcast Receivers

Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcasted as an Intent object.
public class MyReceiver  extends  BroadcastReceiver {

}

Content Providers

A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends  ContentProvider {

}
We will go through these tags in detail while covering application components in individual chapters.

Additional Components

There are additional components which will be used in the construction of above mentioned entities, their logic, and wiring between them. These components are:
ComponentsDescription
FragmentsRepresents a behavior or a portion of user interface in an Activity.
ViewsUI elements that are drawn onscreen including buttons, lists forms etc.
LayoutsView hierarchies that control screen format and appearance of the views.
IntentsMessages wiring components together.
ResourcesExternal elements, such as strings, constants and drawables pictures.
ManifestConfiguration file for the application.

Adjust Text size in All Android Devices?

Today iam try to solve Text size in all Android Devices, last one week am struggle to solve this issue finally found the solution of this issue.

STEP : 1
   first in   ` res` folder =>  values => dimensions.xml=> create  `dimensions.xml`  file to  `values folder`  in that create like below code depending on textsize

         <?xml version="1.0" encoding="utf-8"?>
           <resources>
               <dimen name="textsize">8sp</dimen>
               <dimen name="text">10sp</dimen>
               <dimen name="comments">7sp</dimen>
           </resources>

STEP : 2
   in java file write this line

    TextView textviewtwo = (TextView)findViewById(R.id.sponsertwo_txt);
   textviewtwo.setText("brought to you by");
   textviewtwo.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.textsize));
          // in place of textsize use text and comments what ever we want depending on size. use like text size                  adjust automatically in all devices


ANDROID:BITMAP IMAGE STORE IN EXTERNAL OR INTERNAL STORAGE?

Write this line in onCreate() method, This line of code is used for checking Sd card  is available or not.


  1. Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals
                             (android.os.Environment.MEDIA_MOUNTED);

And this method is used for save your bitmap file in external and internal storage.

  1. private String SaveImage_Sta(Bitmap finalBitmap, String name) {
    if(isSDPresent) {
    Log.i("isSDPresent yes", " path is==> " +isSDPresent );
    String root = Environment.getExternalStorageDirectory().toString() + "/profile";
    File myDir = new File(root);
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = name + ".jpg";
    file = new File(myDir, fname);
    if (file.exists())
    file.delete();
    try {
    FileOutputStream out = new FileOutputStream(file);
    finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    out.flush();
    out.close();

    } catch (Exception e) {
    e.printStackTrace();
    }
        } else {
        
         Log.i("isSDPresent no ", " path is==> false ");
         ContextWrapper cw = new ContextWrapper(getApplicationContext());
             // path to /data/data/yourapp/app_data/imageDir
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            // Create imageDir
            file =new File(directory,"profile.jpg");       
          
            if (file.exists())
    file.delete();
            try {        
             FileOutputStream fos = new FileOutputStream(file);
             finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
             fos.flush();
                fos.close();
            
            } catch (Exception e) {
                e.printStackTrace();
            }       
        }
    return file.toString();


Select DateRange UsingRangePicker.

  /* * This Method is for select range from picker. * */ private fun selectDateRangeUsingRangePicker () { pageNumber = 1 val displ...