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. 

Android Foreground Service Example

How to move a service to foreground?

Answer: call startForeground(int id, Notification notification);

Update UI or toast from IntentService : What will happen if you try to touch U I or try to print a toast message from onHandleIntent() function of IntentService class ?

Answer:  it behaves weirdly, either toast message may not appear or it appears and will be n
ever removed. this happens because other thread is touch ui with out informing to
main thread.If you try to touch other UI components, it will crash.


Description:
it behaves weirdly, either toast message may not appear or it appears and will be never removed. this happens because other threads can't touch UI with out informing to main thread. If you try to touch other UI components, it will crash. IntentService onHandleIntent() functions runs in worker thread (not main thread). So don't try to touch UI elements from that function directly.

can I start a service from worker thread?

Answer: You can start service from any where, but still oncreate, onstartcommand runs in main thread only.

 

To do some back ground functionality in an activity, which is better ? thread or service?

A. thread is better as long as thread is closely related with your UI and as long as programmer make sure that cleaning and creation of thread is done properly.
B. it is better to use services with thread, because threads in activity will have less priority compared to thread in a service in case if that activity is in background or stopped state. more over in case of low memory if it kills thread in activity, there is no way that android will recreate it. all these disadvantages are overcome in services with android.

C. you can either use option 1 or option 2, based on your requirement. But most of the times it is better to use option 2.
D. Both thread and service are back ground components, so you can use either of them.


Answer: C

Description:
it is better to use services with thread, because threads in activity will have less priority compared to thread in a service in case if that activity is in background or stopped state. more over in case of low memory if it kills thread in activity, there is no way that android will recreate it. all these disadvantages are overcome in services with android. But still if you want to use a thread with activity then as long as programmer make sure that cleaning and creation of thread is done properly, then there won't be any problem.

How to achieve security for services programmatically, in such a way that yo ur service should not get triggered from outside applications?

Answer: Don't give any intent-filters for your service tag [or] put exported="false" in service
tag [or] LocalServiceManager


Description :
If you don't want to expose your service to outside apps, 3 ways are there. 1. Don't give intent-fiiter tag, so that outsiders can't specify intent action to trigger your service. or 2. User exported="false" in service tag, so that outside world cant trigger it. or 3. User local service manager.

What is the life cycle of a started service?

Answer: oncreate -> onstartCommand() -> onDestroy()

This is the life cycle of a started service. onBind() and onUnbind() will come into picture for only binded services. previously in old versions onStart() was there in place of onStartCommand().

How to implement binder services, when client applications are in different p rocesses?

Answer: 
Binder is used if both client and server are in same application.

If client and service (server) are in different applications, then this can be implemented in two ways:


1. Messenger - is a simple way to implement binder service, which is single threaded mode.
With this, your service can handle only one client request at a time.


2. aidl (Android interface definition language) - use it if you want multi threaded capability for your server/service.
With this, your service can handle multiple requests at a time. But little complicated.
Make sure that you are writing always thread safe program in your service when using with aidls.
This is not recommended for most of the implementations.

Communication with services

1. Options for communication

There are several possibilities for an activity to communicate with a service and vice versa. This section discusses the possible approaches and provides recommendation which to use.

2. Using Intent data

In a simple scenario no direct communication is required. The service receives the intent data from the starting Android component and performs its work. No notification is necessary. For example, in case the service updates a content provider, the activity is notified by the content provider and no extra step in the service is necessary. This approach works for local and services running in their own process.

3. Using receiver

You can also use broadcast events and registered receivers for the communication. For example, your activity can dynamically register a broadcast receiver for an event and the service sends outs corresponding events. This is a very typical scenario, in which the service need to signal to the activity that his processing has finished.

This communication flow is depicted in the following graphic.
Broadcast receiver used for service to activity communication

Android provides the LocalBroadcastManager class in the support library v4. This is a helper class to register for and send broadcasts of Intents to local objects within your process. This approach improves security as the broadcast events are only visible within your process and is faster than using standard events.  
This approach works for local and services running in their own process.

4. Activity binding to local service

If the service is started in the same process as the activity, the activity can directly bind to the service. This is a relatively simple and efficient way to communicate and recommended for activities which need to have a fast communication layer with the service.
This approach works for local services.

5. Handler and ResultReceiver or Messenger

If the service should be communicating back to the activity, it can receive an object of type Messenger via the Intent data it receives from the activity. If the Messenger is bound to a Handler in the activity, the service can send objects of type Message to the activity.
A Messenger is parcelable, which means it can be passed to another process and you can use this object to send Messages to the Handler in the activity.
Messenger also provides the method getBinder() which allows passing a Messenger to the activity. The activity can therefore send Messages to the service.
This approach works for local services running in their own process.

6. AIDL for services in a different process

To bind to a service which runs in a different process, you need to use Inter Process Communication (IPC) as the data needs to be sent between different processes. To do so, you need to create a AIDL file which looks similar to a Java interface, but ends with the .aidl file extension and is only allowed to extend other AIDL files.
This approach is required if you need to bind to a service running in another process, i.e., if your service is consumed by other Android applications.

You can find more information about this approach in the http://developer.android.com/guide/components/aidl.html- Android developer documentation about AIDL.

Services in separate processes

1. Running a service in its own process

You can also specify that your Service runs in a separate process via the <android:process=":process_description"> attribute.

<service
        android:name="WordService"
        android:process=":my_process"
        android:icon="@drawable/icon"
        android:label="@string/service_name"
        >
</service>

The colon prefix in front of the name tells Android that the Service is private to its declaring application. If the colon is not used, the Service would be a global process and can be used by other Android applications.

Running a service in its own process will not block the application in case the service performs long running operations in its main thread. But as the services runs in its own process, you need to use some interprocess communication (IPC) to communicate to your service from other parts.

Even if the service runs in its own process, you need to use asynchronous processing to perform network access, because Android does not allow network access in the main thread of a process.

5.2. When to run a service in a separate process?

Running a service in its own process gives it its own memory address space and a garbage collector of the virtual machine in this process does not affect the application process.

Application rarely need to run a service in its own process. Running services in its own process makes the communication with other Android components and the service harder to implement.

Note: If you want to make a service to other Android application available, they must run in their own process.

Binding services

1. Binding to services from activities

If the activity wants to interact with the service directly, it can use the bindService() method to start the service.

This method requires a ServiceConnection object as a parameter which is called on the service start and when finishing its onBind() method. This method returns a IBinder object to the ServiceConnection.

This IBinder object can be used by the activity to communicate with the service.

When the binding process has finished, the onStartCommand() method in the service is called with the Intent object used for the bindService() method.

2. Local services bindings

If the service runs in the same process as the activity, it is possible to return the service to the activity. This allows that the activity can call methods of the service directly. This technique is demonstrated by <xref linkend="exercise_bindlocalservice" />.

3. Interprocess communication services bindings

If the service run in its own process, you require IPC (Interprocess Communication) to communicate with the service.

IntentServices for one time tasks

You can also extend the IntentService class for your service implementation.

The IntentService is used to perform a certain task in the background. Once done, the instance of IntentService terminates itself automatically. An example for its usage would be downloading certain resources from the internet.

The IntentService class offers the onHandleIntent() method which will be asynchronously called by the Android system.

Defining custom services


1. Implementation and declaration

A service needs to be declared in the AndroidManifest.xml file and the implementing class must extend the Service class or one of its subclasses.

The following code shows an example for a service declaration and its implementation.
 
<service
        android:name="MyService"
        android:icon="@drawable/icon"
        android:label="@string/service_name"
        >
</service>
 
public class MyService extends Service {

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
          //TODO do something useful
          return Service.START_NOT_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
        //TODO for communication return IBinder implementation
    return null;
  }
}

2. Start a service

An Android component (service, receiver, activity) can trigger the execution of a service via the startService(intent) method.
// use this to start and trigger a service
Intent i= new Intent(context, MyService.class);
// potentially add data to the intent
i.putExtra("KEY1", "Value to be used by the service");
context.startService(i);
 
Alternatively, you can also start a service via the bindService() method call. This allows you to communicate directly with the service. We discuss that later.

3. Service start process and execution

If the startService(intent) method is called and the service is not yet running, the service object is created and the onCreate() method of the service is called.

Once the service is started, the onStartCommand(intent) method in the service is called. It passes in the Intent object from the startService(intent) call.

If startService(intent) is called while the service is running, its onStartCommand() is also called. Therefore your service needs to be prepared that onStartCommand() can be called several times.

What if you call this method twice in your code? Do you have to worry about synchronizing the onStartCommand() method call? No, this method is called by the Android system in the main user interface thread, therefore it cannot be called simultaneously from two different threads.
A service is only started once, no matter how often you call the startService() method.

4. Service restart behavior

In its onStartCommand() method call, the service returns an int which defines its restart behavior in case the service gets terminated by the Android platform. You can use the constants, the most common options are described by the following table.
Table 1. Restart options
Option Description
Service.START_STICKY
Service is restarted if it gets terminated. Intent data passed to the onStartCommand method is null. Used for services which manages their own state and do not depend on the Intent data.
Service.START_NOT_STICKY
Service is not restarted. Used for services which are periodically triggered anyway. The service is only restarted if the runtime has pending startService() calls since the service termination.
Service.START_REDELIVER_INTENT
Similar to Service.START_STICKY but the original Intent is re-delivered to the onStartCommand method.
You can check if the service was restarted via the Intent.getFlags() method. START_FLAG_REDELIVERY (in case the service was started with Service.START_REDELIVER_INTENT) or START_FLAG_RETRY (in case the service was started with Service.START_STICKY) is passed.

5. Stopping a service

You stop a service via the stopService() method. No matter how frequently you called the startService(intent) method, one call to the stopService() method stops the service.
A service can terminate itself by calling the stopSelf() method. This is typically done if the service finishes its work.