ANDROID
ANDROID
ANDROID
Mobile Computing
Using
S.S.S.D.I.I.T College
Junagadh
ANDROID & IPHONE topics:
Intro, Application design, interface design, Database Connectivity, location based service, notification, service
deployment, intro IPHONE.
Developed By:
Ripal Pandya
9427696988
youtube.com/avadhtutor
pandyaripal.blogspot.com
Introduction to Android
History of Android
Android founded in palo alto, california, united state in october 2003. By Andy Rubin(Co-
Founder of danger), rich miner(Co- Founder of wildfire communication), nick sears (once VP
at T-Mobile) and Chris white(Headed design and interface development at web TV) to
develop Android.
What is ANDROID:
- It is a open source software platform and operating System for Mobile Device.
- Android is based on Linux kernel.
- Developed by Google and later the Open Handset Alliance(OHA).
- Allow writing manage Code in the Java Language.
- Android has its own machine. i.e: DVM(Dalvik Virtual Machine), which is used for
executing the android application.
- Google purchased the initial developer of the software, android incorporated in
2005.
Features of android:
- Background Wi-Fi location still runs even when Wi-Fi is turned off
- Developer logging and analyzing enhancements
- It is optimized for mobile devices.
- It enables reuse and replacement of components.
- Java support ,media support, multi touch, video calling,multi tasking ,voice based features,
screen capture, camera ,bluetooth,gps,compass and accelerometer,3G
Advantages of Android:
- The ability for anyone to customize the Google Android platform
- It gives you better notification.
- It lets you choose your hardware.
- It has better app market(1,80,000 application)
- A more mature platform
- With the support of many applications, the user can change the screen display.
- With Google chrome you can open many window at once.
- Supports all Google services: Android operating system supports all of Google services
ranging from Gmail to Google reader. all Google services can you have with one operating
system, namely Android.
Limitation of android:
- Development requirements in
- Java
- Android SDK
- Eclipse IDE (optional)
- Bluetooth limitations:-
- Android doesn't support:
- Bluetooth stereo
- Contacts exchange
- Modem pairing
- Wireless keyboards
- Firefox mobile isn't coming to android because of android limitations
- Apps in Android Market need to be programmed with a custom form of Java
- → Mozilla and the Fennec won't have that
- There are no split or interval times available.
- Small memory size.
- Continuous Internet connection is required
- The latest version of Android is code named Jelly Bean and kitkat.
- Android is open Source.
o Samsung, motorola, vodafone, htc, LG, Dell, asus, acer, docomo, nec, sharp, sony
ericsion, toshiba, ebay, google, intel, ARM, sprint etc…
Android Architecture:
The software stack is split into four layer:
- Application layer
- Application framework.
- The libraries and run time.
- The kernel.
Linux kernel:
Native Libraries:
- these library can’t access directly. With the help of application framework, we can access
this library.
- Android Runtime:
o android runtime designed specifically for android to meet the needs for running in
an embedded environment where you have limited battery, limited memory, limited
CPU.
o Davik is the process virtual machine in google’s android operating system. It is
software that runs the apps on android devices.
o Program are commonly written in java and compiled to byte Code.
o The core libarary contains all of the collection classes, utilities, IO, all the utilities and
tools that your come to expected to use.
Application Framework:
- This is all written in java programming language and the application framework is the toolkit
that all application use.
- These application include the once that come with a phone like home application, or the
phone application.
- It includes application written by google and it include apps that will be written you.
Application Layer:
To Develop android application, you need to have the following software installation on your
computer:
o Java development Kit(JDK): android is work with Java so install JDK 5 or 6 version
download on http://java.sun.com/javase/download/index.jsp
o Java IDE such as eclipse: eclipse is a tool to developed a application.
o Android SDK (Software Development Kit): tools and Document available on
http://developer.android.com/sdk/
o Android Development tools(ADT):that’s provide plugin for eclipse. Cnfigure and run
android environment using ADT this is available on http://developer.android.com
- Upgrade Android SDK:
o Android SDK upgrade time to time. You can easily upgrade the android SDK and
tools from within eclipse using the android SDK and AVD manager.
- Exploring the Android SDK:
o Understanding the licence agreement.
Right granted
SDK usage
SDK changes and backward compatibility
Android developer rights, application privacy, Google APIs.
- Android Terminology
- Application Context, Activities,Services, intents
- Receving and Broadcasting Intents.
Android terminology:
- Context: The context is the central command center for an Android application. All
application-specific functionality can be accessed through the context.
- Activity: An Android application is a collection of tasks, each of which is called an Activity.
Each Activity within an application has a unique task or purpose.
- Intent:The Android operating system uses an asynchronous messaging mechanism to match
task requests with the appropriate Activity. Each request is packaged as an Intent.You can
think of each such request as a message stating an intent to do something.
- Service: Tasks that do not require user interaction can be encapsulated in a service.A service
is most useful when the operations are lengthy (offloading time-consuming processing) or
need to be done regularly (such as checking a server for new mail).
Context:
o getApplicationContext(),
o getContext(),
o getBaseContext()
o or this (when in the activity class).
- Example of Context:
o Creating New objects: Creating new views, adapters, listeners
TextView tv = new TextView(getContext());
ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),
...);
getApplicationContext().getSharedPreferences(*name*, *mode*);
They are both instances of Context, but the application instance is tied to the lifecycle of the
application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to
different information about the application environment.
If you read the docs at getApplicationContext it notes that you should only use this if you need a
context whose lifecycle is separate from the current context.
Activity:
Callback Description
onCreate() This is the first callback and called when the activity is first created.
onStart() This callback is called when the activity becomes visible to the user.
onResume() This is called when the user starts interacting with the application.
The paused activity does not receive user input and cannot execute any code and called when
onPause()
the current activity is being paused and the previous activity is being resumed.
onDestroy() This callback is called before the activity is destroyed by the system.
onRestart() This callback is called when the activity restarts after stopping it.
Service:
A service is a component that runs in the background to perform long-running operations without needing to
interact with the user.
State Description
Method of Service:
Callback Description
The system calls this method when another component, such as an activity,
requests that the service be started, by calling startService(). If you implement this
onStartCommand()
method, it is your responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.
The system calls this method when another component wants to bind with the
service by calling bindService(). If you implement this method, you must provide
onBind() an interface that clients use to communicate with the service, by returning
anIBinder object. You must always implement this method, but if you don't want to
allow binding, then you should return null.
The system calls this method when all clients have disconnected from a particular
onUnbind()
interface published by the service.
The system calls this method when new clients have connected to the service,
onRebind() after it had previously been notified that all had disconnected in
itsonUnbind(Intent).
The system calls this method when the service is first created
onCreate() usingonStartCommand() or onBind(). This call is required to perform one-time
setup.
The system calls this method when the service is no longer used and is being
onDestroy()
destroyed. Your service should implement this to clean up any resources such as
Intent:
Context.startActivity()
1 The Intent object is passed to this method to launch a new activity or get an existing activity to
do something new.
Context.startService()
2 The Intent object is passed to this method to initiate a service or deliver new instructions to an
ongoing service.
Context.sendBroadcast()
3 The Intent object is passed to this method to deliver the message to all interested broadcast
receivers.
- Intent Object:
o Action:
This is mandatory part of the Intent object and is a string naming the action to be
performed.
The action in an Intent object can be set by the setAction() method and read by
getAction().
o Data:
The URI of the data to be acted on and the MIME type of that data.
The setData() method specifies data only as a URI, setType() specifies it only as a
MIME type, and setDataAndType() specifies it as both a URI and a MIME type. The
URI is read by getData() and the type by getType().
- Types of intent:
o Explicit Intents:
These intents designate the target component by its name and they are typically used
for application-internal messages - such as an activity starting a subordinate service
or launching a sister activity.
For example:
// Starts TargetActivity
startActivity(i);
o Implecit Intents:
These intents do not name a target and the field for the component name is left blank.
Implicit intents are often used to activate components in other applications. For
example:
- There are following two important steps to make BroadcastReceiver works for the systen broadcasted
intents:
} }
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
- Every Android project includes a special file called the Android manifest file.
- The Android system uses this file to determine application configuration settings, which
includes Application’ identity like its name and version.
- Also includes permissions the application requires to run.
- named AndroidManifest.xml, is an XML file that must be included at the top level of any
Android project.
- Android system uses the information in this file to do the following task:
Android manifest file is a specially formatted XML file. Generally manifest file
include single <manifest> tag with a single <application> tag.
- AndroidManifest.xml
- This file tells us that application uses the package name com.androidbook.multimedia.
- Application version name is 1.0.
- Application version code is 1.
- Application name are stored in resource string called @string/app_name within the
/res/values/strings.xml resource file.
- The application is debuggable on an Android device. Means it will debugged when it is
running on device.
- The application icon is the graphic file called icon stored within the /res/drawable directory.
- The application has five activities MultimediaMenuActivity, AudioActivity, VideoPlayActivity
etc.
- The application requires following permission to run :-
o Ability to record audio.
o Ability to set wall paper on the device.
o Ability to access the built in camera
- Intent Filter:
o Set Entry Point Activity for your Application Using a Intent Filter …
o An Activity class can be specify as primary entry point for application using <intent-
filter> tag specify with MAIN as action type and LAUNCHER as category.
<activity android:name=“.AudioActivity”>
<intent-filter> <action android:name=“android.intent.action.MAIN”/>
<category android:name=“android.intent.category.LAUNCHER” />
<intent-filter> </activity>
- Permission:
o Android applications have no permissions by default
o Permission can be set using <uses-permission> tag inside Android Manifest file
o Example:
Android Resources:
What is Android Resource:
- Android resource files are stored separately from the java class files in the Android
project.
<set>,<alpha>, <scale>,
fadsequence.xml
Tweened Animations /res/anim/
pinsequence.xml
<translate> <rotate>
Frame by Frame
/res/drawable/ sequence1.xml sequence2.xml <animation-list><item>
Animations
sunrahahai.mp3
Raw Files /res/raw/ -----------
Tumhiho.mp3
- The aapt traverses all properly formatted files in the /res directory hierarchy and generates
the class file R.java in the android project /gen directory.
- simple resource value types, such as strings, colors, dimensions, and other primitives are
stored under the /res/values/ directory in XML files.
- To store string and color types value you have to use <resources> tag, and under that you
can use <string> and <color> tag to specify string and color resources respectively.
Property:
Android:capitalize: If set, specifies that this TextView has a textual input method and should
automatically capitalize what the user types.
Android:inputType: The type of data being placed in a text field. Phone, Date, Time, Number, Password etc.
Android:textColor: Text color. May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb"
Android:textSize: Size of the text. Recommended dimension type for text is "sp" for scaled-pixels (example:
15sp).
Android:textStyle: Style (bold, italic, bolditalic) for the text. You can use or more of the following values
separated by '|'.
Example:
Activity_main.xml
<TextView
android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:capitalize="characters"
android:text="@string/hello_world" />
MainActivity.java
});
}
Property:
Android:autotext: If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.
Example:
Activity_main.xml
<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1"
android:layout_marginTop="61dp"
android:ems="10"
android:text="EditText" android:inputType="text" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="130dp"
android:text="Click Me" />
MainActivity.java
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String str = eText.getText().toString();
Toast msg = Toast.makeText(getBaseContext(),str,
Toast.LENGTH_LONG);
msg.show();
msg.show();
}
});
}
Property:
android:autoText: If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.
android:onClick: This is the name of the method in this View's context to invoke when the view is clicked.
Example:
Activity_main.xml
<EditText <EditText
android:id="@+id/edittext" android:id="@+id/edittext"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1" android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/textView1" android:layout_below="@+id/textView1"
android:layout_marginTop="61dp" android:layout_marginTop="61dp"
android:ems="10" android:ems="10"
android:inputType="text" android:inputType="text"
android:text="@string/enter_text1" /> android:text="@string/enter_text1" />
<EditText
android:id="@+id/edittext3" <Button
android:layout_width="fill_parent" android:id="@+id/button1"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_alignLeft="@+id/edittext" android:layout_height="wrap_content"
android:layout_below="@+id/edittext2" android:layout_alignLeft="@+id/textView1"
android:layout_marginTop="14dp" android:layout_below="@+id/edittext3"
android:ems="10" android:layout_marginTop="35dp"
android:inputType="text" android:text="@string/click_button" />
android:text="@string/enter_text3" />
MainActivity.java
edText1 = (EditText)findViewById(R.id.edittext);
edText2 = (EditText)findViewById(R.id.edittext2);
edText3 = (EditText)findViewById(R.id.edittext3);
btnProduct = (Button)findViewById(R.id.button1);
btnProduct.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String t1 = edText1.getText().toString();
String t2 = edText2.getText().toString();
String t3 = edText3.getText().toString();
int i1 = Integer.parseInt(t1);
int i2 = Integer.parseInt(t2);
int i3 = Integer.parseInt(t3);
TimePicker: Android Time Picker allows you to select the time of day in either 24 hour
or AM/PM mode. The time consists of hours, minutes and clock format. Android
provides this functionality through TimePicker class.
Methods of TimePicker:
is24HourView()
1
This method returns true if this is in 24 hour view else false
isEnabled()
2
This method returns the enabled status for this view
setCurrentHour(Integer currentHour)
3
This method sets the current hour
setCurrentMinute(Integer currentMinute)
4
This method sets the current minute
setEnabled(boolean enabled)
5
This method set the enabled state of this view
setIs24HourView(Boolean is24HourView)
6
This method set whether in 24 hour or AM/PM mode
setOnTimeChangedListener(TimePicker.OnTimeChangedListener
7 onTimeChangedListener)
This method Set the callback that indicates the time has been adjusted by the user
Example:
}
public void setTime(View view) {
int hour = timePicker1.getCurrentHour();
int min = timePicker1.getCurrentMinute();
showTime(hour, min);
}
public void showTime(int hour, int min) {
if (hour == 0) {
hour += 12;
format = "AM";
} else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
time.setText(new StringBuilder().append(hour).append(" : ").append(min)
.append(" ").append(format));
}
Spinner: spinner which allows to select an item from a drop down menu.
Example:
Activity_main.xml
<!-- Spinner Element -->
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/spinner_title"
/>
MainActivity.java
public class AndroidSpinnerExampleActivity extends Activity implements OnItemSelectedListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinner);
Android layouts: A layout may contain any type of widgets such as buttons, labels, textboxes, and
so on.
Attribute Description
This must be a boolean value, either "true" or "false" and prevents the layout
android:baselineAligned
from aligning its children's baselines.
This is drawable to use as a vertical divider between buttons. You use a color
android:divider
value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
This specifies how an object should position its content, on both the X and Y
android:gravity axes. Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc.
This specifies the direction of arrangmet and you will use "horizontal" for a
android:orientation
row, "vertical" for a column. The default is horizontal.
Example: Activity_main.xml File
<Button android:id="@+id/btnStartService"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="@string/start_service"
<Button android:id="@+id/btnPauseService"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="@string/pause_service"
</LinearLayout>
- Relative layout:
o RelativeLayout is a view group that displays child views in relative positions.
o Relative Layout Attributes:
Attribute Description
This specifies how an object should position its content, on both the X and Y
android:gravity axes. Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder" />
<TextView
android:id="@+id/dates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times" />
</RelativeLayout>
- Table Layout:
o TableLayout is a view that groups views into rows and columns.
o Following are the important attributes specific to TableLayout:
Attribute Description
This specifies the zero-based index of the columns to collapse. The column
android:collapseColumns
indices must be separated by a comma: 1, 2, 5.
The zero-based index of the columns to shrink. The column indices must be
android:collapseColumns
separated by a comma: 1, 2, 5.
The zero-based index of the columns to stretch. The column indices must
android:stretchColumns
be separated by a comma: 1, 2, 5.
o Example:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow>
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
- Absolute Layout:
o AbsoluteLayout enables you to specify the exact location of its children.
o Following are the important attributes specific to AbsoluteLayout:
Attribute Description
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="OK"
android:layout_x="50px"
android:layout_y="361px" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_x="225px"
android:layout_y="361px" />
</AbsoluteLayout>
- Frame layout:
Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 27
S.S.S.D.I.I.T – College Android & I Phone B.C.A
o The FrameLayout is a placeholder on screen that you can use to display a single view.
o Following are the important attributes specific to FrameLayout:
Attribute Description
This defines the drawable to draw over the content and possible values
android:foreground may be a color value, in the form of "#rgb", "#argb", "#rrggbb", or
"#aarrggbb".
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="@drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_height="250px"
android:layout_width="250px"/>
<TextView
android:text="Frame Demo"
android:textSize="30px"
android:textStyle="bold"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
Note: Other Layout’s are Grid View and ListView
o Using Android Data and Storage API, Managing Data Using SQLite, Content Provider.
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 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.
If your application creates a database, this database is by default saved in the directory :
DATA/data/APP_NAME/databases/FILENAME .
SQLITE ARCHITECTURE:
Note: Both methods receive an SQLiteDatabase object as parameter which is the Java representation of the database.
SQLite Database:
o SQLiteDatabase is the base class for working with a SQLite database in Android and
provides methods to open, query, update and close the database.
o More specifically SQLiteDatabase provides
o In addition it provides the execSQL() method, which allows to execute an SQL statement
directly.
o The object ContentValues allows to define key/values. The key represents the table
column identifier and the value represents the content for the table record in this
column. ContentValues can be used for inserts and updates of database entries.
o Queries can be created via the rawQuery() and query() methods or via
the SQLiteQueryBuilder class .
rawQuery() directly accepts an SQL select statement as input.
Parameter Comment
String[] A list of which table columns to return. Passing "null" will return all
columnNames columns.
String whereClause Where-clause, i.e. filter for the selection of data, null will select all
data.
String[] selectionArgs You may include ?s in the "whereClause"". These placeholders will get
replaced by the values from the selectionArgs array.
String[] groupBy A filter declaring how to group rows, null will cause the rows to not be
grouped.
String[] orderBy Table columns which will be used to order the data, null means no ordering.
Cursor:
Simple Example:
Ex1:
Ex2:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
onCreate(db);
}
APPLICATION PREFERENCES:
Android provides a simple preferences system for storing primitive application data at the
Activity level and preferences shared across all of an application’s activities. Preferences are stored
as groups of key/value pairs.The following data types are supported as preference settings:
- Boolean value
- Float value
- Integer value
- Long Value
- String Value
PRIVATE PREFERENCES:
Individual activities can have their own private preferences.These preferences are for the specific
Activity only and are not shared with other activities within the application.The activity gets only one
group of private preferences.
The following code retrieves the activity’s private preferences:
import android.content.SharedPreferences;
...
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
SHARED PREFERENCES:
SharedPreferences is an API from Android SDK to store and retrieve
application preferences. SharedPreferences are simply sets of data values that stored persistently.
Persistently which mean data you stored in the SharedPreferences are still exist even if you stop the
application or turn off the device.
Creating shared preferences is similar.The only two differences are that we must name our
preference set and use a different call to get the preference instance:
import android.content.SharedPreferences;
clear()
It will remove all values from the editor
remove(String key)
It will remove the value whose key has been passed as a parameter
EXAMPLE:
Main_Activity.xml
MainActivity.java
public class InternalStoreActivity extends Activity {
/** Called when the activity is first created. */
EditText editTextFileName,editTextData;
Button saveButton,readButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextFileName=(EditText)findViewById(R.id.editText1); editTextData=(EditText)findViewById(R.id.editText2);
saveButton=(Button)findViewById(R.id.button1); readButton=(Button)findViewById(R.id.button2);
saveButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) { String filename=editTextFileName.getText().toString();
String data=editTextData.getText().toString(); FileOutputStream fos;
try { fos = openFileOutput(filename, Context.MODE_PRIVATE); fos.write(data.getBytes()); fos.close();
Toast.makeText(getApplicationContext(),filename + " saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
} }); readButton.setOnClickListener(new OnClickListener(){
@Override public void onClick(View arg0) { String filename=editTextFileName.getText().toString();
StringBuffer stringBuffer = new StringBuffer();
try { BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput(filename))); String inputString;
while ((inputString = inputReader.readLine()) != null) { stringBuffer.append(inputString + "\n"); }
} catch (IOException e) { e.printStackTrace();
}Toast.makeText(getApplicationContext(),stringBuffer.toString(),Toast.LENGTH_LONG).show(); }
}); } }
EXTERNAL STORAGE:
It would be useful to save them to external storage (such as an SD card) because of its larger
capacity, as well as the capability to share the files easily with other users (by removing the SD card
and passing it to somebody else).
Example:
MainActivity.xml
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity.java
public class ExternalStorageExActivity extends Activity {
/** Called when the activity is first created. */
EditText editTextFileName,editTextData;
Button saveButton,readButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextFileName=(EditText)findViewById(R.id.editText1); editTextData=(EditText)findViewById(R.id.editText2);
saveButton=(Button)findViewById(R.id.button1); readButton=(Button)findViewById(R.id.button2);
saveButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
String filename=editTextFileName.getText().toString(); String data=editTextData.getText().toString();
FileOutputStream fos;
try {
File myFile = new File("/sdcard/"+filename); myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data); myOutWriter.close(); fOut.close();
Toast.makeText(getApplicationContext(),filename + " saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();} } });
readButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) { String filename=editTextFileName.getText().toString();
StringBuffer stringBuffer = new StringBuffer(); String aDataRow = ""; String aBuffer = "";
try { File myFile = new File("/sdcard/"+filename); FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n"; } myReader.close(); } catch (IOException e) { e.printStackTrace();
} Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show(); } }); } }
CONTENT PROVIDER IN ANDROID
- Android using a Content Provider is the recommended way to share data across packages. Think of content
provider as a data store. How it stores its data is not relevant to the application using it;
- What is important is how packages can access the data stored in it using a consistent programming interface.
- A content Provider behaves very much like a database – you can Query it, edit its content, as
well as add or delete content. However, unlike a database, a content provider can use
different way to store its data. The data can be stored in a database, in files, or even over a
network.
Android Ships with many useful content providers, including the following:
- Browsers: Stores data such as browser bookmarks, browser history, and so on.
- CallLog: Store data such as missed calls, call detail and so on.
- Contacts: Stores contact details.
- MediaStore: Stores media files such as audio, video and images.
- Settings: Stores the devices setting and preferences.
HOW TO HANDLE CONTENT PROVIDER:
- Standard prefix for content providers is always content: //.
- Handle Content Provider using Query String.
- Examples of Query String:
o Content://media/internal/images
o Content://call_log/calls
o Content://browser/bookmarks
Predefined Query String Constants of Content Provider:
Besides using the query URI, you can use a list of predefined query string constant in android to specify the URI for the
different data types.
Uri allcontacts = Url.parse(‘content://contacts/people’);
Some examples of predefined query String:
- Browser.BOOKMARKS_URI
- Browser.SEARCH_URI
- CallLog.CONTENT_URI
- MediaStore.Images.Media.INTERNAL_CONTENT_URI
- Setting.CONTENT_URI
values.put(StudentsProvider.NAME,
((EditText)findViewById(R.id.txtName)).getText().toString());
values.put(StudentsProvider.GRADE,
((EditText)findViewById(R.id.txtGrade)).getText().toString());
Toast.makeText(getBaseContext(),
uri.toString(), Toast.LENGTH_LONG).show(); }
public void onClickRetrieveStudents(View view) {
// Retrieve student records
String URL = "content://com.example.provider.College/students";
Uri students = Uri.parse(URL);
Cursor c = managedQuery(students, null, null, null, "name");
if (c.moveToFirst()) {
do{ Toast.makeText(this,
c.getString(c.getColumnIndex(StudentsProvider._ID)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),
Toast.LENGTH_SHORT).show();
} while (c.moveToNext());
} } }
StudentProvider.java
package com.contentProv;
import java.util.HashMap;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
/**
* Database specific constant declarations
*/
private SQLiteDatabase db;
static final String DATABASE_NAME = "College";
static final String STUDENTS_TABLE_NAME = "students";
static final int DATABASE_VERSION = 1;
static final String CREATE_DB_TABLE =
" CREATE TABLE " + STUDENTS_TABLE_NAME +
/**
* Helper class that actually creates and manages
* the provider's underlying data repository.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_DB_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME);
onCreate(db);
} }
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)){
case STUDENTS:
count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs);
break;
case STUDENT_ID:
String id = uri.getPathSegments().get(1);
count = db.delete( STUDENTS_TABLE_NAME, _ID + " = " + id +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
} getContext().getContentResolver().notifyChange(uri, null);
return count; }
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)){
/**
* Get all student records
*/
case STUDENTS:
return "vnd.android.cursor.dir/vnd.example.students";
/**
* Get a particular student
*/
case STUDENT_ID:
return "vnd.android.cursor.item/vnd.example.students";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri); } }
@Override
public Uri insert(Uri uri, ContentValues values) {
/**
* Add a new student record
*/
long rowID = db.insert( STUDENTS_TABLE_NAME, "", values);
/**
* If record is added successfully
*/
if (rowID > 0)
{ Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null); return _uri; }
throw new SQLException("Failed to add a record into " + uri); }
@Override
The Global Positioning System (GPS) is a space-based satellite navigation system that
provides location and time information in all weather conditions, anywhere on or near the
Earth where there is an unobstructed line of sight to four or more GPS satellites.
WHAT IS GEOCODING?
Geocoding (sometimes called forward geocoding) is the process of enriching a description
of a location, most typically a postal address or place name, with geographic
coordinates from spatial reference data such as building polygons, land parcels, street
addresses, ZIP codes (postal codes) and so on. Geocoding facilitates spatial analysis
using Geographic Information Systems and Enterprise Location Intelligence systems.
Query for the list of all LocationProviders for the last known user location.
Register/unregister for periodic updates of the user's current location from a location provider
(specified either by criteria or name).
Register/unregister for a given Intent to be fired if the device comes within a given proximity
(specified by radius in meters) of a given lat/long.
GOOGLE MAP ANDROID API
- With the Google Maps Android API, you can add maps to your app that are based on Google
Maps data. The API automatically handles access to Google Maps servers, data downloading,
map display, and touch gestures on the map. You can also use API calls to add markers,
polygons and overlays, and to change the user's view of a particular map area.
- The key class in the Google Maps Android API is MapView. A MapView displays a map with
data obtained from the Google Maps service. When the MapView has focus, it will capture
keypresses and touch gestures to pan and zoom the map automatically, including handling
network requests for additional maps tiles. It also provides all of the UI elements necessary
for users to control the map. Your application can also use MapView class methods to
control the map programmatically and draw a number of overlays on top of the map.
Step2: Go to www.code.google.com/apis/console
Step3: Create Finger Print by using the key tool and Debug File
Step5: In this step you just copy thus SHA1 key from cmd and paste on the Google console of
configure android key for API project with your android project package name.
Step 6: So here we start the create the new project name "GoogleMapLocationAPIV2
"GoogleMapLocationAPIV2" and set the
target with Google API and add the Google play service library project with this project. See the
screen shot.
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class LocationAddress {
private static final String TAG = "LocationAddress";
public static void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler) {
Thread thread = new Thread() {
@Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n\nAddress:\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n Unable to get address for this lat-long.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
Step4: Android UI
MainActivity.Java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MyActivity extends Activity {
Button btnGPSShowLocation;
Button btnShowAddress;
TextView tvAddress;
AppLocationService appLocationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
tvAddress = (TextView) findViewById(R.id.tvAddress);
appLocationService = new AppLocationService(
MyActivity.this);
.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
String result = "Latitude: " + gpsLocation.getLatitude() +
" Longitude: " + gpsLocation.getLongitude();
tvAddress.setText(result);
} else {
showSettingsAlert();
}
}
});
btnShowAddress = (Button) findViewById(R.id.btnShowAddress);
btnShowAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
//you can hard-code the lat & long if you have issues with getting it
//remove the below if-condition and use the following couple of lines
//double latitude = 37.422005;
//double longitude = -122.084095
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
} else {
showSettingsAlert();
}
}
});
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MyActivity.this);
alertDialog.setTitle("SETTINGS");
alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MyActivity.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
The WebView control uses the WebKit rendering engine to draw HTML content on the
screen.This content could be HTML pages on the Web or it can be locally sourced.
You can add this permission to your application’s Android manifest file as follows:
<uses-permission android:name=”android.permission.INTERNET” />
Examples:
Ex1: Displaying Layout with Web View Control
<WebView
android:id=”@+id/web_holder”
android:layout_height=”wrap_content”
android:layout_width=”fill_parent”/>
Coding:
final WebView wv = (WebView) findViewById(R.id.web_holder);
wv.loadUrl(“http://www.perlgurl.org/”);
- You can use the CallLog.calls class to determine recent call information, such as
Who called, When they called, Whether it was an incoming or outgoing call
Whether or not anyone answered, The duration of the call
- An application listening to SMS in this way doesn’t prevent the message from getting to
other applications.
Notification
Introduction:
Android allows putting notification into the title bar of your application. The user can expand the
notification bar and by selecting the notification the user can trigger another activity.
Types of Notification:
- User Notification
- Status bar Notification
- Customizing Notification
Setting us Notification:
Notifications in Android are represented by the Notification class.
To create notifications you use the NotificationManager class which can be received from
the Context , e.g. an activity or a service, via the getSystemService() method.
Example:
Notification Property:
- A small icon, set by setSmallIcon()
- A title, set by setContentTitle()
- Detail text, set by setContentText()
Example:
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
NotificationCompat.Builder Class:
Notificationbuild()
Combine all of the options that have been set and return a new Notification object.
NotificationCompat.BuildersetContent(RemoteViewsviews)
Supply a custom RemoteViews to use instead of the standard one.
NotificationCompat.BuildersetContentIntent(PendingIntentintent)
Supply a PendingIntent to send when the notification is clicked.
NotificationCompat.BuildersetContentText(CharSequencetext)
Set the text (second row) of the notification, in a standard notification.
NotificationCompat.BuildersetWhen(longwhen)
Set the time that the event occurred. Notifications in the panel are sorted by this time.
Example of Notification:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this);
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You've received new message.");
mBuilder.setTicker("New Message Alert!");
mBuilder.setSmallIcon(R.drawable.woman);
/* Increase notification number every time a new notification arrives */
mBuilder.setNumber(++numMessages);
ONLINE:
Step1: Create GOOGLE ACCOUNT
Step2: Login on Google Developer Account
Step3: Bank and Price Detail Pay 25$ on Account Creation
______________________________________________________________
2. Intent (Navigation) :
https://www.youtube.com/watch?v=r3lU5DZ5TDU&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs
05A_Oqa&index=20
8. Share Button:
https://www.youtube.com/watch?v=G3ZBM1iM-
kI&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs05A_Oqa&index=36
10 Activity Animation
https://www.youtube.com/watch?v=s-
bQVZswH_g&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs05A_Oqa&index=43