Wednesday, 20 April 2016

Difference between Service, Threads & AsyncTask

Hi All.


After long time, again I have to something for write and share.

You can find many documents, post, blogs and discussion on this topic but I think if we have all the stuff at one place it is better to understand.

So I will try to my best to put the all things which covers the all thing for this topic.

So far, we have a way for applications to implicitly do work in the background, as long as the process doesn't get killed by Android as part of its regular memory management. This is fine for things like loading web pages in the background, but what about features with harder requirements? Background music playback, data synchronization, location tracking, alarm clocks, etc.


Service:
  • Service is a Android component without UI.
  • A Service allows an application to implement longer-running background operations. The fundamental purpose is for an application to "continue running even while in the background, until it done."
  • While services do provide a rich client-server model, its use is optional. Upon starting an application's services, Android simply instantiates the component in the application's process to provide its context. How it is used after that is up to the application: it can put all of the needed code inside of the service itself without interacting with other parts of the application, make calls on other singleton objects shared with other parts of the app, directly retrieve the Service instance from elsewhere if needed, or run it in another process and do a full-blown RPC protocol if that is desired.
  • Because an unbounded number of services can ask to be running for an unknown amount of time. There may not be enough RAM to have all of the requesting services run, so as a result no strong guarantees are made about being able to keep them running.
  • If there is too little RAM, processes hosting services will be immediately killed like background processes are. However, if appropriate, Android will remember that these services wish to remain running, and restart their process at a later time when more RAM is available. For example, if the user goes to a web page that requires large amounts of RAM, Android may kill background service processes like sync until the browser's memory needs go down.
  • Services can further negotiate this behaviour by requesting they be considered "foreground." This places the service in a "please don't kill" state, but requires that it include a notification to the user about it actively running. This is useful for services such as background music playback or car navigation, which the user is actively aware of; when you're playing music and using the browser, you can always see the music-playing glyph in the status bar. Android won't try to kill these services, but as a trade-off, ensures the user knows about them and is able to explicitly stop them when desired.
  • Service never runs in a dedicated /thread/. By default it runs in the main application thread, and may optionally run in a separate /process.
  • If you need to have something to keep on running while the user goes from one of your activities to the other, then you may also need a service.
  • Thread must be "embedded" in the service, not the opposite. The service acts as an entry point, in which you can create. several threads if you like.
Note: 
  • In Android, even if the Service runs in the background, it runs on the Main Thread of the application. So, if at the same time if you have an activity displayed, the running service will take the main thread and the activity will seem slow. It is important to note that a Service is just a way of telling Android that something needs to run without a user interface in the background while the user may not interacting with your application. So, if you expect the user to be interacting with the application while the service is running and you have a long task to perform in a service, you need to create a worker thread in the Service to carry out the task.
  • Services are a way to tell Android that certain code in your application is important to the user, and Android should make an effort to keep it running even when it doesn't have active activities.
  • Your service will want to spawn its own thread or asynctask to do your heavy work or else you will get a forceclose.


Service
Thread
IntentService
AsyncTask
When to use ?
Task with no UI, but shouldn't be too long. Use threads within service for long tasks.
- Long task in general.

- For tasks in parallel use Multiple threads (traditional mechanisms)
- Long task usually with no communication to main thread.
(Update)- If communication is required, can use main thread handler or broadcast intents

- When callbacks are needed (Intent triggered tasks). 
- Small task having to communicate with main thread.

- For tasks in parallel use multiple instances OR Executor
 
Trigger
Call to method
onStartService()
Thread start() method
Intent
Call to method execute()
Triggered From (thread)
Any thread
Any Thread
Main Thread (Intent is received on main thread and then worker thread is spawed)
Main Thread
Runs On (thread)
Main Thread
Its own thread
Separate worker thread
Worker thread. However, Main thread methods may be invoked in between to publish progress.
Limitations /
Drawbacks
May block main thread
- Manual thread management

- Code may become difficult to read
- Cannot run tasks in parallel.

- Multiple intents are queued on the same worker thread.
- one instance can only be executed once (hence cannot run in a loop) 

- Must be created and executed from the Main thread

Friday, 27 March 2015



1. SQLite and Android

What is SQLite?

SQLite is an Open Source database. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. The database requires limited memory at runtime (approx. 250 KByte) which makes it a good candidate from being embedded into other runtimes.
SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long in Java) and REAL(similar to double in Java). All other types must be converted into one of these fields before getting saved in the database. SQLite itself does not validate if the types written to the columns are actually of the defined type, e.g. you can write an integer into a string column and vice versa.

SQLite in Android

SQLite is embedded into every Android device. Using an SQLite database in Android does not require a setup procedure or administration of the database.
You only have to define the SQL statements for creating and updating the database. Afterwards the database is automatically managed for you by the Android platform.
Access to an SQLite database involves accessing the file system. This can be slow. Therefore it is recommended to perform database operations asynchronously.
If your application creates a database, this database is by default saved in the directoryDATA/data/APP_NAME/databases/FILENAME.
The parts of the above directory are constructed based on the following rules. DATA is the path which theEnvironment.getDataDirectory() method returns. APP_NAME is your application name. FILENAME is the name you specify in your application code for the database.


Creating and updating database with SQLiteOpenHelper

To create and upgrade a database in your Android application you create a subclass of the SQLiteOpenHelperclass. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.
In this class you need to override the following methods to create and update your database.
  • onCreate() - is called by the framework, if the database is accessed but not yet created.
  • onUpgrade() - called, if the database version is increased in your application code. This method allows you to update an existing database schema or to drop the existing database and recreate it via theonCreate() method.
Both methods receive an SQLiteDatabase object as parameter which is the Java representation of the database.
The SQLiteOpenHelper class provides the getReadableDatabase() and getWriteableDatabase()methods to get access to an SQLiteDatabase object; either in read or write mode.
The database tables should use the identifier _id for the primary key of the table. Several Android functions rely on this standard.



SQLiteDatabase is the base class for working with a SQLite database in Android and provides methods to open, query, update and close the database.
More specifically SQLiteDatabase provides the insert()update() and delete() methods.
In addition it provides the execSQL() method, which allows to execute an SQL statement directly.
The object ContentValues allows to define key/values. The key represents the table column identifier and thevalue represents the content for the table record in this column. ContentValues can be used for inserts and updates of database entries.
Queries can be created via the rawQuery() and query() methods or via the SQLiteQueryBuilder class .
rawQuery() directly accepts an SQL select statement as input.
query() provides a structured interface for specifying the SQL query.
SQLiteQueryBuilder is a convenience class that helps to build SQL queries.



rawQuery() Example

The following gives an example of a rawQuery() call.

return database.query(DATABASE_TABLE, 
  new String[] { KEY_ROWID, KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION }, 
  null, null, null, null, null);
 


Parameters of the query() method
ParameterComment
String dbNameThe table name to compile the query against.
String[] columnNamesA list of which table columns to return. Passing "null" will return all columns.
String whereClauseWhere-clause, i.e. filter for the selection of data, null will select all data.
String[] selectionArgsYou may include ?s in the "whereClause"". These placeholders will get replaced by the values from the selectionArgs array.
String[] groupByA filter declaring how to group rows, null will cause the rows to not be grouped.
String[] havingFilter for the groups, null means no filter.
String[] orderByTable columns which will be used to order the data, null means no ordering.

If a condition is not required you can pass null, e.g. for the group by clause.
The "whereClause" is specified without the word "where", for example a "where" statement might look like: "_id=19 and summary=?".
If you specify placeholder values in the where clause via ?, you pass them as the selectionArgs parameter to the query.


3.6. Cursor

A query returns a Cursor object. A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory.
To get the number of elements of the resulting query use the getCount() method.
To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. TheisAfterLast() method allows to check if the end of the query result has been reached.
Cursor provides typed get*() methods, e.g. getLong(columnIndex)getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing.
Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table.
Cursor needs to be closed with the close() method call.

Cursor is not a class but an interface. If your Cursor object is from a SQLite query, it is a SQLiteCursor. In that definition (\Android\android-sdk\source\android\database\sqlite\SQLiteCursor.java)close() is called in the finalize() function. This may be different in other cursor types, since the Cursor interface does not specify this behavior.

You can close the cursor once you have retrieved the values for that particular object inside your method.

 ListViews, ListActivities and SimpleCursorAdapter

ListViews are Views which allow to display a list of elements.
ListActivities are specialized activities which make the usage of ListViews easier.
To work with databases and ListViews you can use the SimpleCursorAdapter. TheSimpleCursorAdapter allows to set a layout for each row of the ListViews.
You also define an array which contains the column names and another array which contains the IDs of Viewswhich should be filled with the data.
The SimpleCursorAdapter class will map the columns to the Views based on the Cursor passed to it.
To obtain the Cursor you should use the Loader class.

Haystack TV Doubles Engagement with Android TV | Android Developers Blog

Haystack TV Doubles Engagement with Android TV | Android Developers Blog

Monday, 19 May 2014

What is Android ?

Android is an operating system based on the Linux kernel with a user interface based on direct manipulation, designed primarily fortouchscreen mobile devices such as smartphones and tablet computers, using touch inputs, that loosely correspond to real-world actions, like swiping, tapping, pinching, and reverse pinching to manipulate on-screen objects, and a virtual keyboard. Despite being primarily designed for touchscreen input, it also has been used in televisions, games consoles, digital cameras, and other electronics.

As of 2011, Android has the largest installed base of any mobile OS and as of 2013, its devices also sell more than Windows, iOS and Mac OS devices combined.As of July 2013 the Google Play store has had over 1 million Android apps published, and over 50 billion apps downloaded.A developer survey conducted in April–May 2013 found that 71% of mobile developers develop for Android.

Android's source code is released by Google under open source licenses, although most Android devices ultimately ship with a combination of open source and proprietary software.Initially developed by Android, Inc., which Google backed financially and later bought in 2005,Android was unveiled in 2007 along with the founding of the Open Handset Alliance—​a consortium of hardware, software, and telecommunication companies devoted to advancing open standards for mobile devices. Android is popular with technology companies which require a ready-made, low-cost and customizable operating system for high-tech devices. Android's open nature has encouraged a large community of developers and enthusiasts to use the open-source code as a foundation for community-driven projects, which add new features for advanced users or bring Android to devices which were officially released running other operating systems. The operating system's success has made it a target for patent litigation as part of the so-called "smartphone wars" between technology companies.

Overal Definations

Android is a comprehensive software stack of mobile devices that includes an operating system, middleware and key application. This rich source of software bunch is used in Mobile Technology through its innovation module of The Android Software Development Kit (SDK).

Open Handset Alliance

Open Handset Alliance is an amalgamation of Tech Companies with common and particular interest in the mobile user enhancement experience. Companies like Google, HTC, Motorola, Samsung, Telecom Italia, T Mobile, LG, Texas Instruments as well as Sony Ericsson, Vodafone, Toshiba and Hawaii are Tech giant based on their core abilities and strengths, while keeping and pursuing the characters and goals of each company, their basic idea of this joining of hands was the feature-rich mobile experience for the end user. This alliance meant the sharing of ideas and innovation, to bring out these ideas into reality. This provided the millions and millions of Mobile users the experience that they never had.
Like the Apple iphone, Android Operating System allows third party developers to innovate and create Applications and software for mobile devices. Android is an open, flexible and stable enough to associate itself with newer and newer evolving Technologies. Android’s vast range of easy to use tools and wide range of libraries provides Mobile Application developers with the means of an amazing mobile operating software to come up with the most efficient and rich Mobile Applications changing the world of millions of mobile users.