Android Update UI Periodically Using data from Service

Android Service And Its LifeCycle

Android Save And Restore Instance On Configuration Change

Fragments

Android Parsers

Storage

Android Volley

Background Services

Unbound Service Vs Bound Service Vs IntentService

Android Handler Example

Android SQLite Database Tutorial

How to Use Hindi Font in Android Application

Creating a Background Service in Android Using IntentService

Android Service Example

Android Third Party Libraries and SDK’s

JSON Feed Reader in Android

Handler and AsyncTask in Android

Android Interview Questions And Answers

Android Interview Question Answers For Freshers

Android Service Interview Questions

Loader tutorials

Inner Class tutorials

Keeping Your App Responsive

Processes and Threads

Android Networking Tutorial

List of HTTP status codes

HTTP Methods: GET vs. POST

Retrofit Android Library Tutorial

OKHttp tutorials

SQLite

How to use SQLite Database in Android
How to use SQLite Database in Android
 How to use SQLite Database in Android
How to use SQLite Database in Android
How to use SQLite Database in An
How to use SQLite Database in Androidfsa
How to use SQLite Database in Android

Awesome Android Complete Reference

What are intents?

Intents are asynchronous messages which allow application components to request functionality from other Android components. Intents allow you to interact with components from the same applications as well as with components contributed by other applications. For example, an activity can start an external activity for taking a picture.
Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining the components you are targeting. For example, via the startActivity() method you can define that the intent should be used to start an activity.
An intent can contain data via a Bundle. This data can be used by the receiving component.
In Android the reuse of other application components is a concept known as task. An application can access other Android components to achieve a task. For example, from a component of your application you can trigger another component in the Android system, which manages photos, even if this component is not part of your application. In this component you select a photo and return to your application to use the selected photo.



When activity is moved to stopped state, then what will happen to the life cy cle of a fragment which is in that activity?

Answer: fragments will be moved to onStop

Description: Since fragments are part of an Activity always, when Activity is moved to stopped state, then automatically fragments in it will be moved to stopped state.

Note: Fragments life cycle will be affected by activity's life cycle.

Fragment Lifecycle Management


  • onAttach() :This method will be called first, even before onCreate(), letting us know that your fragment has been attached to an activity. You are passed the Activity that will host your fragment
 
  • onCreateView() : The system calls this callback when it’s time for the fragment to draw its UI for the first time. To draw a UI for the fragment, a View component must be returned from this method which is the root of the fragment’s layout. We can return null if the fragment does not provide a UI
 
  • onViewCreated() : This will be called after onCreateView(). This is particularly useful when inheriting the onCreateView() implementation but we need to configure the resulting views, such as with a ListFragment and when to set up an adapter
 
  • onActivityCreated() :This will be called after onCreate() and onCreateView(), to indicate that the activity’s onCreate() has completed. If there is something that’s needed to be initialised in the fragment that depends upon the activity’s onCreate() having completed its work then onActivityCreated() can be used for that initialisation work
 
  • onStart() : The onStart() method is called once the fragment gets visible
 
  • 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() : It’s called before onDestroy(). This is the counterpart to onCreateView() where we set up the UI. If there are things that are needed to be cleaned up specific to the UI, then that logic can be put up in onDestroyView()
 
  • onDestroy() : onDestroy() called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.
 
  • onDetach() : It’s called after onDestroy(), to notify that the fragment has been disassociated from its hosting activity

Primary Classes Related to Android Fragment

Fragments were added to the Android API in Honeycomb(API 11).
  • android.app.Fragment : The base class for all fragment definitions
  • android.app.FragmentManager : The class for interacting with fragment objects inside an activity
  • android.app.FragmentTransaction : The class for performing an atomic set of fragment operations
When using a compatibility package library provided by Google, the following classes are used for implementation.

  • android.support.v4.app.FragmentActivity : The base class for all activities using compatibility-based fragment (and loader) features
  • android.support.v4.app.Fragment
  • android.support.v4.app.FragmentManager
  • android.support.v4.app.FragmentTransaction

Fragment life-cycle

A fragment has its own life cycle. But it is always connected to the life cycle of the activity which uses the fragment.
Fragment lifecycle
If an activity stops, its fragments are also stopped. If an activity is destroyed, its fragments are also destroyed.
Table Title
Method Description
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()
Fragment is created. The onCreate() method is called after the onCreate() method of the activity but before the onCreateView() method of the fragment.
onCreateView()
The fragment instance creates its view hierarchy. In the onCreateView() method the fragment creates its user interface. Here you can inflate a layout via the inflate() method call of the Inflator object passed as a parameter to this method.
In this method you should not interactive with the activity, the activity is not yet fully initialized.
There is no need to implement this method for headless fragments .The inflated views become part of the view hierarchy of its containing activity.
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()
Fragment is visible but becomes not active anymore, e.g., if another activity is animating on top of the activity which contains the fragment.
onStop()
Fragment becomes not visible.
onDestroyView()
Destroys the view of the fragment. If the fragment is recreated from the backstack this method is called and afterwards the onCreateView method.
onDestroy()
Not guaranteed to be called by the Android platform.

Fragments and Context access

Fragments don’t subclass the Context class. Therefore you have to use the getActivity() method to get the parent activity.

What are fragments?

Fragments is a new concept introduced in 3.0 version.

The basic purpose of fragments is:

1. Fragments are designed to use the device UI space efficiently.
When you are writing an application in android, then some people can download it into phone, some into tablets. If you see the space in tablets it will be little bigger than phones. You should be able to use that space efficiently. But you can't keep writing different applications one targeting for phone, and other targeting for tablets. In order to do it efficiently, i.e writing only application that can fit well with all screen sizes, we use fragments concept.

2. fragments are designed as a reusable UI components between more than one activity.
Once you design a fragment, you can view it as a detachable independent unit, so that you can plug it into any activity where ever there is a space. That means you can reuse the code designed for a fragment.

Fragment you can think of it like a sub activity, which sits with in an activity and which contributes its own UI to the activity screen.
Fragments are always part of an activity. With out an activity, a fragment will not exist. So your fragment life cycle will always be affected by activity life cycle.
An activity can contain more than one fragment. Similarly a fragment can be re used in multiple activities.

Note: It is also possible to define fragments without an user interface, i.e., headless fragments.

In which thread asynctask functions will execute?

A. all four functions executes in worker thread context.
B. all four functions executes in main thread context.
C. onPreExecute, onProgressUpdate, onPostExecute - runs in background thread, doInBackGround - runs in MainThread
D. onPreExecute, onProgressUpdate, onPostExecute - runs in Main thread, doInBack
Ground - runs in background Thread

Answer: D

How to create a service with single thread? should I use IntentService or As yncTask?

A. Use IntentService, if you don't want to interact with UI.
B. Use AsyncTask if you want to interact with UI.
C. both option 1 and option 2 are correct.
D. none


Answer: C

Description: 
It actually depends on the requirement. Use IntentService, if you don't want to interact with UI. Use AsyncTask if you want to interact with UI from background thread. It doesn't mean that you can't touch UI from IntentService, but you have to either use post() or runOnUiThread() or Handler concepts, which are little bit complicated to understand for novice android developers who are not well versed with threads.

how many threads will be created with asynctask?

Answer: till donut - it is used to create single thread, from 1.6 to 2.3 - it is used to create multi threads, from 3.0 on wards - it is again used to create single thread.

Description: 
till donut - it is used to create single thread, from 1.6 to 2.3 - it is used to create multi threads, from 3.0 on wards - it is again used to create single thread. If you want to create multiple threads with asynctask from 3.0 on wards, instead of using execute(), use executeOnExecutor(Executor e, variable). They have reverted back the basic functionality if asynctask.execute() to behave as a single threaded, because multi threded programming will lead to lot of complications in terms of synchronization. 

what will happen if execute() function of asynctask is called more than once, for a give asynctask object?

Answer: we should not call execute more than once on one object, it will throw run time exception.

Is it possible to start asynctask from background thread?

Answer: it is mandatory that one has to call asynctask only from main thread, else it may crash at run time when we try to touch UI from onPreExecute [or] onProgressUpdate [or] onPostExecute functions.

Why android follows single threaded UI model?

Answer: Because synchronization is costly compared to single threaded model.

Description: using synchronization also it is possible to manipulate UI from other threads. But Android doesn't follow that design, because it is very costly in terms of CPU time over head if we use synchronization. So all UI updates has to go through Main Thread (or UI thread) only.

Define AsyncTask?How many methods are there and how parameters work in it?

Answer: 
The AsyncTask class is a way to achieve multi-threading in android application, where multiple tasks can be run at a time. It synchronizes with the main thread. It also supports reporting progress of the running tasks.

There are four methods in Async Task:
1. onPreExecute()
2. doInBackground()
3. onUpdateProgress()
4. onPostExecute()
 

The three types of parameters in AsyncTask:
1. Params: the type of the parameters sent to the task upon execution.
2. Progress: the type of the progress units published during the background compu
tation.
3. Result: the type of the result of the background computation.

What is a thread?Is service with Thread possible?

Answer: Thread is a dispatch able unit to the CPU.All Java programs have at least one thread, known as the main thread. Yes Service with thread is possible. But by default service will run in main thread.

How to stop a thread in android?

Answer:  Use a volatile Boolean flag, based on which return from the run() method of the Thread.

What is the difference between synchronized block(statement) and synchro nized methods?

Answer:
i. syn method - all statements in this are synchronized
syn block - only this block of code is synchronized, not whole method.


ii. syn method - if already any thread is holding lock on this function's object then other threads can't call another syn method on same object.
syn block - If a function is having 1000 lines and I access shared data only in 5,6th line, then better to put syn block than making whole function as
synchronized.

How to avoid synchronization problems in threads?

Answer: To avoid synchronized problems with multi threaded programs, use synchronized block or synchronized methods, which ever suits better.

What is the difference between task, process, application, and thread?

Process - every instance of an application being executed is called as process. You execute same application two times, it will create 2 processes.

Application - is generalized term of a process.

Task - can have one or more applications in it. 

eg: task of sending a message : we will start with message application, lets say i want to attach a photo to my message, then i will open gallery application also. In this case my task has got two applications, messaging and gallery application.

Thread - theoretically thread is a light weight process, or part of process.Practically thread is dispatch-able unit to CPU, and it is internal part of a process. With out a thread in your program it is difficult to execute your application.application. That's why by default every process will have at least one thread created by Operating system.

Create a thread in the activity and stop that activity, then what will happen t o that thread, will it be alive or dead?

Answer: it will be alive, but its priority will be least compared to thread in a service.


Description:  once a thread is created, it will run independently of who has created until the work given to that thread is finished. but in case of low memory scenarios a thread created by activity and which is running in the background will have more susceptibility of being killed by android system. More worse is android can not recreate the thread which was killed because of low memory. but if that thread was in service, then chances of getting killed by android due to low memory may be less than previous situation. even if android system kills the thread, again it will start the service when memory resources are available and service can re-initiate that killed thread.

How Android inter thread communication works?

Inter thread communication : means passing some data between threads.

Every thread internally will have 2 components: Looper & Message queue.


Message Queue : is to store incoming messages


Looper : will keep checking message queue to respond to those messages. Without Looper, it is not possible to achieve Inter thread communication.


Only Handler Threads will have loopers.

Normal Java threads will also have loopers but they will be in the passive mode. (Since looper is passive it cannot check message queue for new incoming message).
Since your looper is not active in java threads so they cannot handle inter thread communication.                           
You can enable the looper by calling looper.prepare().

So, Inter thread communication is possible through only Handler Threads. Because Handler threads allows message passing mechanism through loopers.

There is one more technique to have Inter thread communication.
Share some data in some common storage, and allow both the threads to access that data by using some synchronization mechanism like wait, notify.
This is possible with normal java threads also.

How binder is different from serialization?

Answer: Binder uses shared memory concept to do Inter process communication

Description: Serialization and Binders are both IPC mechanisms how to processes will communicate. Serialization is very heavy as it has to copy hole data and transmit to other process through channel. But Binders are light weight where both the processes will share or communicate the data using a shared memory concept. what ever the data has to be shared it will be kept in a common shared memory and both process's can access that memory to make communication faster.

What is the mechanism used by android for Inter-process-communication?

IPC means Inter process communication : Where two applications or processes will communicate with each other by passing some data between them.

Since android is meant for embedded and small devices, we should not use serialization for IPC, rather we can use BINDERs which internally uses parcels. parcel is a sort of light weight serialization by using shared memory concept.

There are many differences between Binder IPC and Serialization IPC:
1. Serialization is very heavy to use in embedded devices, communication will be very slow.
2. Binders uses Parcels to make IPC very fast.
3. Binders internally uses Shared memory concept which uses less memory while sharing data between two processes.

Bottom line : Binders uses less memory, and quite fast as it uses parcels. Serialization is very heavy , takes time to send and receive data, and also it takes more memory compared to binders.

Note : To pass data between activities, services, and receivers use only Bundles. Don't go for either serialization or binders.
            Binders are specifically used only for binder services where 2 processes will communicate.

Does android support multithreading?

Answer: Yes it supports both multi tasking and multi threading.

Description: Yes it supports both multitasking and multi-threading. User can launch multiple applications at a time and can switch between those applications (this is called as multitasking). In a given application we can have multiple threads which can run simultaneously (this is called as multi-threading).

Does android support multitasking? How multitasking works in android, explain how to start a new task when you are already running a task?

Description: 
Android supports multitasking at app level also. That means you can create apps with multitasking capability. One way to achieve multitasking is press home button on current task which will move it to background and then you can start new task from launcher.Another way is use FLAG_NEW_TASK in the intent, when you are starting a new activity.

Note: User can press and hold home button to see all the starting activities of recent tasks he has visited. From there also user can switch to other tasks by selecting any of those activities.

How to update UI from other threads? Note : Other thread means other than main thread.

Answer:  Request Main Thread through inter thread communication using Handlers or runOnUiThread() function, and manipulate ui

Description: All UI controls or views will be under control of Main thread (UI thread). If other thread wants to touch UI, it is possible through one of the inter thread communication, that is through handlers or through runOnUiThread() function or through asynctask.

 

If I have one application with activity, service, and contentprovider. Then when I run this program how many process, threads will be created? Is it possible to run these components in more than one process?

Answer: One process, one Thread, Yes it is possible to run in more than one process.

Description: Before loading an application into RAM, a process will be created with a thread by default. Even though in Linux, an application will be given only one process to run all its components, it is quite possible that components of a given application can run in more than one process provided both processes have same Linux user id.

What is ANR (application not responding)? What is the reason for this probl em and what is the solution for that problem?

Answer: ANR - will occur if we are doing any other heavy functionality along with UI in single Main Thread. If two heavy functionalities happen in single thread, it will delay response to user actions, which may irritate user, and hence stop your process.

Solution - Run only UI components in Main Thread.

Trigger broadcast receiver only if my activity is in memory, else it should not get triggered, how to do it?

Answer: Register a dynamic receiver in that Activity.

Description: If you want to trigger broadcast receiver as long as activity is in memory, then go for dynamic receiver which gets registered only when activity comes into memory. and unregister it before killing your activity.

How set an alarm to trigger after two days? how to implement it? assume tha t user may switch off the phone in between.

Answer: Use AlarmManager and call set() to set after 2 days. Even phone switches off nothing will happen.

Description:
Use AlarmManager and call set() to set after 2 days. If phone switched off, all alarms will be dead. So, before switching off maintain all alarms details in Data Base and recreate all alarms after switching on.

How to send BATTERY_LOW broadcast? should I use sendbroadcast() or s endstickybroadcast? Why?

Answer: use sendStickyBroadCast(), because logically this broadcast has to be available fo
r future users.


Description: We have to use sendStickyBroadCast() because, logically if battery went down, then this information has to be available for applications which may run after some time in future.

How to create a receiver without registering it in manifest file?

Answer: We can register receiver dynamically in code.

Description: Every component has to get registered in the manifest file. But there is an exception for this rule, a broadcast receiver can get registered dynamically in code. Because there may be some scenarios where we need handle broadcasted messages only when our application is running. If we register it in manifest file statically, then even if our app is not running, it may trigger our broadcast receiver.

 

To notify something to the user from a broadcast receiver, should I use dial ogs or notifications? Why?

Answer: Use Notifications, cause Receivers has to finish its functionality in 10 seconds

Description: Broadcast receivers are light weight components, which has to finish off its functionality with in time limit of 10 seconds. if we show dialog to user, there is a chance that user may take more than 10 seconds to respond to it by chance. in that case receiver may crash or may not be available to take dialog input from user. So it is always a standard and good practice to use notifications from a receiver.

What is the life cycle of a broadcast receiver in android?

Answer: onReceive()

Description:  there is only one function in broad cast receiver, that is onReceive(). Broadcast receiver's life will start before calling onReceive() method, and once control comes out of onReceive() method, then it will be killed.

What is the difference between sendbroadcast(), sendorderedbroadcast(), sendstickybroadcast() ?

Answer:
sendbroadcast() - normal broadcast, but we can set priority as well.
sendorderedbroadcast() - we can set priority, and set result. can block broadcasts as well.
sendstickybroadcast() - intent passed with this will be stick for future users

Description:
sendbroadcast() - normal broadcast, but we can set priority as well.

sendorderedbroadcast() - we can set priority, and set result. can block broadcasts as well.
In the ordered broadcast you can predict the order of broadcast receiver using priority in the intent_ Filter.
1.If the priority is same for two receivers then order cannot be predicted.
2.In the ordered broadcast you can also pass data between two receivers.
3.You can also abort the broadcast anywhere in between the receivers.

sendstickybroadcast() - intent passed with this will be stick for future users who are registering through code (dynamic receivers).
When somebody sends a sticky broadcast using send stickyBroadcast(in); then that broadcast will be available for the future users who are using dynamic receivers.
This broadcast will be available for only Dynamic Broadcast rx who are coming in future.

Eg for stickybroadcast is - BATTERY LOW.



What is the difference between broadcast receiver and a service?

BroadcastReceiver - is like gateway for other components, can do small back ground functionality within 10 seconds. Services - can do long running operation in the background with out having UI, and no time limit for it.but both receiver and service both can interact with UI if they want to. services will not have time limit of 10 seconds, receivers respond to broadcasted messages.

Is it possible to start a service from a broadcast receiver?

Answer: yes can start using startService() function

Description: Any component can communicate with other component. only exception for this rule is don't bind to a service from a broad cast receiver. other wise one is free to start a service.

What will happen if broad cast receiver binds to binder service? Is there any problem?

Description: 

One should not bind a service from Broadcast receiver. The reason is broadcast receivers are light weight components, where it has to finish its functionality with in not more than 10 seconds maximum. Else android may forcefully kill your receiver. Binding (establishing connection to) a service may take more than 10 seconds in some worst cases, that's why android won't allow it.

Rules for Broadcast Receivers:

1.Broadcast receivers will not have any UI(mostly) and it will have only background logic.


2.Broadcast receivers will have the maximum time limit of 10 sec to finish its functionality otherwise it will crash.


3.You should not do long running operations or asynchronous operations in the receiver.


Example: a. Preparing SD card. b. Uploading / Downloading files from internet. c. Creating Db files. d. Binding to services
 

4.Do not show dialog to the user in broadcast receiver. (this is asynchronous operation)

5.You can use “ toast” or “Notifications”.


6.Don’t write any heavy functionalities.

Broadcast receiver runs in which thread, by default?

Answer: Main thread

Description: Default every component of android will run in Main thread (UI thread). So broadcast receiver also runs in main thread by default.

An application is having one broadcast receiver - whose onReceive() is currently executing, service - is in running state; then what is that process priority?

Answer: foreground process(1)

Description: Receiver which is executing its onReceive() will be treated with highest priority. process priority will be the maximum of components priority. So in this case process priority is highest priority.

Dynamic broadcast receiver registration

1. Dynamically registered receiver

Receiver can be registered via the Android manifest file. You can also register and unregister a receiver at runtime via the Context.registerReceiver() and Context.unregisterReceiver() methods.

Note: Do not forget to unregister a dynamically registered receiver by using Context.unregisterReceiver() method. If you forget this, the Android system reports a leaked broadcast receiver error. For instance, if you registered a receive in onResume() methods of your activity, you should unregister it in the onPause() method. 

2. Using the package manager to disable static receivers

You can use the PackageManager class to enable or disable receivers registered in your AndroidManifest.xml file.

ComponentName receiver = new ComponentName(context, myReceiver.class);
PackageManager pm = context.getPackageManager();

pm.setComponentEnabledSetting(receiver,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP);

3. Sticky (broadcast) intents

An intent to trigger a receiver ( broadcast intent ) is not available anymore after it was sent and processed by the system. If you use the sendStickyBroadcast(Intent) method, the corresponding intent is sticky, meaning the intent you are sending stays around after the broadcast is complete.
The Android system uses sticky broadcast for certain system information. For example, the battery status is send as sticky intent and can get received at any time. The following example demonstrates that.

// Register for the battery changed event
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

/ Intent is sticky so using null as receiver works fine
// return value contains the status
Intent batteryStatus = this.registerReceiver(null, filter);

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
        || status == BatteryManager.BATTERY_STATUS_FULL;

boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
 
You can retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter)' . This also works for a null `BroadcastReceiver .
In all other ways, this behaves just as sendBroadcast(Intent) .
Sticky broadcast intents typically require special permissions.
 

Exercise: System services and receiver

6.1. Target

In this chapter we will schedule a receiver via the Android alert manager system service. Once called, it uses the Android vibrator manager and a popup message (Toast) to notify the user.

6.2. Implement project

Create a new project called de.vogella.android.alarm with the activity called AlarmActivity .
Create the following layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Number of seconds"
        android:inputType="numberDecimal" >
    </EditText>

    <Button
        android:id="@+id/ok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startAlert"
        android:text="Start Counter" >
    </Button>

</LinearLayout>
Create the following broadcast receiver class. This class will get the vibrator service.
package de.vogella.android.alarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
                Toast.makeText(context, "Don't panik but your time is up!!!!.",
                                Toast.LENGTH_LONG).show();
                // Vibrate the mobile phone
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(2000);
        }

}
Register this class as a broadcast receiver in AndroidManifest.xml and request authorization to vibrate the phone.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.vogella.android.alarm"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <uses-permission android:name="android.permission.VIBRATE" >
    </uses-permission>

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".AlarmActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="MyBroadcastReceiver" >
        </receiver>
    </application>

</manifest>
Change the code of your AlarmActivity class to the following. This activity creates an intent to start the receiver and register this intent with the alarm manager service.
package de.vogella.android.alarm;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class AlarmActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
        }

        public void startAlert(View view) {
                EditText text = (EditText) findViewById(R.id.time);
                int i = Integer.parseInt(text.getText().toString());
                Intent intent = new Intent(this, MyBroadcastReceiver.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(
                                this.getApplicationContext(), 234324243, intent, 0);
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                                + (i * 1000), pendingIntent);
                Toast.makeText(this, "Alarm set in " + i + " seconds",
                                Toast.LENGTH_LONG).show();
        }

}

6.3. Validate implementation

Run your application on the device. Set your time and start the alarm. After the defined number of seconds a Toast should be displayed. Keep in mind that the vibration alarm does not work on the Android emulator.
Alarm application running

Exercise: Register a receiver for incoming phone calls

1. Target

In this exercise you define a broadcast receiver which listens to telephone state changes. If the phone receives a phone call, then our receiver will be notified and log a message.

2. Create project

Create a new project called de.vogella.android.receiver.phone . Also create an activity.
TIP:Remember that your receiver is only called if the user started it once. This requires an activity.

3. Implement receiver for the phone event

Create the MyPhoneReceiver class.
package de.vogella.android.receiver.phone;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

public class MyPhoneReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
                Bundle extras = intent.getExtras();
                if (extras != null) {
                        String state = extras.getString(TelephonyManager.EXTRA_STATE);
                        Log.w("MY_DEBUG_TAG", state);
                        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                                String phoneNumber = extras
                                                .getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                                Log.w("MY_DEBUG_TAG", phoneNumber);
                        }
                }
        }
}

4. Request permission

Add the android.permission.READ_PHONE_STATE permission to your manifest file which allows you to listen to state changes in your receiver. Also Register your receiver in your manifest file. The resulting manifest should be similar to the following listing.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.vogella.android.receiver.phone"
    android:versionCode="1"
    android:versionName="1.0" >

     <uses-sdk android:minSdkVersion="15" />

    <uses-permission android:name="android.permission.READ_PHONE_STATE" >
    </uses-permission>

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
           <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="MyPhoneReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" >
                </action>
            </intent-filter>
        </receiver>
    </application>



</manifest>

5. Validate implementations

Install your application and simulate a phone call via the Android Device Monitor. Validate that your receiver is called and logs a message to the LogCat view.

Pending Intent

A pending intent is a token that you give to another application (e.g., notification manager, alarm manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code.

To perform a broadcast via a pending intent, get a PendingIntent via the getBroadcast() method of the PendingIntent class. To perform an activity via a pending intent, you receive the activity via PendingIntent.getActivity() .

 

Automatically starting Services from a Receivers

A common requirement is to automatically start a service after a system reboot, i.e., for synchronizing data. For this you can register a receiver for the android.intent.action.BOOT_COMPLETED system event. This requires the android.permission.RECEIVE_BOOT_COMPLETED permission.

The following example demonstrates the registration for the BOOT_COMPLETED event in the Android manifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.vogella.android.ownservice.local"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".ServiceConsumerActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="MyScheduleReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <receiver android:name="MyStartServiceReceiver" >
        </receiver>
    </application>

</manifest>
 
The receive would start the service as demonstrated in the following example code.
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
                // assumes WordService is a registered service
                Intent intent = new Intent(context, WordService.class);
                context.startService(intent);
        }
}

Note:
1) If your application is installed on the SD card, then it is not available after the android.intent.action.BOOT_COMPLETED event. In this case register it for the `android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE ` event. 

2) Remember that as of Android API level 11 the user needs to have started the application at least once before your application can receive android.intent.action.BOOT_COMPLETED events.


System broadcasts

Several system events are defined as final static fields in the Intent class. Other Android system classes also define events, e.g., the TelephonyManager defines events for the change of the phone state.

The following table lists a few important system events.




Restrictions for defining broadcast receiver

As of Android 3.1 the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage ▸ Application ).

This is an additional security feature as the user can be sure that only the applications he started will receive broadcast intents.

Asynchronous processing in Broadcast receiver

Before API level 11, you could not perform any asynchronous operation in the onReceive() method, because once the onReceive() method had been finished, the Android system was allowed to recycle that component. If you have potentially long running operations, you should trigger a service instead.

Since Android API 11 you can call the goAsync() method. This method returns an object of the PendingResult type. The Android system considers the receiver as alive until you call the PendingResult.finish() on this object. With this option you can trigger asynchronous processing in a receiver. As soon as that thread has completed, its task calls finish() to indicate to the Android system that this component can be recycled.

Implementation Broadcast receiver

Implementation

A receiver can be registered via the AndroidManifest.xml file.

Alternatively to this static registration, you can also register a receiver dynamically via the Context.registerReceiver() method.

The implementing class for a receiver extends the BroadcastReceiver class.

If the event for which the broadcast receiver has registered happens, the onReceive() method of the receiver is called by the Android system.

What is Broadcast receive

broadcast receiver (short receiver ) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.

For example, applications can register for the ACTION_BOOT_COMPLETED system event which is fired once the Android system has completed the boot process.

How to create a service with multiple threads in it?


What is the difference between service and a thread?

Answer: Service - is a component of android, which runs in the background with out any UI.

By default service will run in Main thread only. Thread - is not android component, but still one can use thread to do some background task. Using thread in place of service is discouraged.


Description: 
Service : is a component of android which performs long running operation in the background, mostly without having UI.

Thread : is a O.S level feature that allow you to do some operation in the background.

Though conceptually both looks similar there are some crucial differentiation.

1.Service - if it is destroyed while performing its job, in the middle by Android due to low memory scenario. Then android will make sure that it will restart your service, if you have returned START_STICKY or START_REDELIVER_INTENT from onStartCommand().


2.Thread - if it is destroyed by android in middle due to low memory, then android will not guarantee to restart it again. That means user lost his half work. 


3.Service - is a component of android, so it has priority levels to be considered while destroying an application due to low memory. Thread- is not a component of android, so android will not take thread priority into consideration while killing an application due to low memory.

I will try to explain this 3rd point.

Lets say you have a requirement of connecting to internet from your activity. You can do it by using a service(with thread) or directly by creating a thread in activity. Consider the second scenario where you are connecting to internet in a thread. Then

i. What will happen if user closes the activity, while still thread is running in the background. Will that thread continue to run in back ground ? Answer is you can't really predict.

ii.Assume that in continuation for above scenario, even after killing activity your thread continued to do its intended operation. Then there is a low memory situation arises in your phone. Then this application will be the first susceptible app to be killed as there is no priority for this application.

So bottom line is: If you want to do some heavy background functionality then it is always better to have a service with thread. If you feel that that background functionality to be alive as long as your activity is alive, then go for activity with thread or activity with async task.