Android – Broadcast Receivers ”; Previous Next Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action. There are following two important steps to make BroadcastReceiver works for the system broadcasted intents − Creating the Broadcast Receiver. Registering Broadcast Receiver There is one additional steps in case you are going to implement your custom intents then you will have to create and broadcast those intents. Creating the Broadcast Receiver A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onReceive() method where each message is received as a Intent object parameter. public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, “Intent Detected.”, Toast.LENGTH_LONG).show(); } } Registering Broadcast Receiver An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process. Broadcast-Receiver <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> Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be executed. There are several system generated events defined as final static fields in the Intent class. The following table lists a few important system events. Sr.No Event Constant & Description 1 android.intent.action.BATTERY_CHANGED Sticky broadcast containing the charging state, level, and other information about the battery. 2 android.intent.action.BATTERY_LOW Indicates low battery condition on the device. 3 android.intent.action.BATTERY_OKAY Indicates the battery is now okay after being low. 4 android.intent.action.BOOT_COMPLETED This is broadcast once, after the system has finished booting. 5 android.intent.action.BUG_REPORT Show activity for reporting a bug. 6 android.intent.action.CALL Perform a call to someone specified by the data. 7 android.intent.action.CALL_BUTTON The user pressed the “call” button to go to the dialer or other appropriate UI for placing a call. 8 android.intent.action.DATE_CHANGED The date has changed. 9 android.intent.action.REBOOT Have the device reboot. Broadcasting Custom Intents If you want your application itself should generate and send custom intents then you will have to create and send those intents by using the sendBroadcast() method inside your activity class. If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete. public void broadcastIntent(View view) { Intent intent = new Intent(); intent.setAction(“com.tutorialspoint.CUSTOM_INTENT”); sendBroadcast(intent); } This intent com.tutorialspoint.CUSTOM_INTENT can also be registered in similar way as we have regsitered system generated intent. <application android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <receiver android:name=”MyReceiver”> <intent-filter> <action android:name=”com.tutorialspoint.CUSTOM_INTENT”> </action> </intent-filter> </receiver> </application> Example This example will explain you how to create BroadcastReceiver to intercept custom intent. Once you are familiar with custom intent, then you can program your application to intercept system generated intents. So let”s follow the following steps to modify the Android application we created in Hello World Example chapter − Step Description 1 You will use Android studio to create an Android application and name it as My Application under a package com.example.tutorialspoint7.myapplication as explained in the Hello World Example chapter. 2 Modify main activity file MainActivity.java to add broadcastIntent() method. 3 Create a new java file called MyReceiver.java under the package com.example.tutorialspoint7.myapplication to define a BroadcastReceiver. 4 An application can handle one or more custom and system intents without any restrictions. Every intent you want to intercept must be registered in your AndroidManifest.xml file using <receiver…/> tag 5 Modify the default content of res/layout/activity_main.xml file to include a button to broadcast intent. 6 No need to modify the string file, Android studio take care of string.xml file. 7 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity file MainActivity.java. This file can include each of the fundamental life cycle methods. We have added broadcastIntent() method to broadcast a custom intent. package com.example.tutorialspoint7.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // broadcast a custom intent. public void broadcastIntent(View view){ Intent intent = new Intent(); intent.setAction(“com.tutorialspoint.CUSTOM_INTENT”); sendBroadcast(intent); } } Following is the content of MyReceiver.java: package com.example.tutorialspoint7.myapplication; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * Created by TutorialsPoint7 on 8/23/2016. */ public class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, “Intent Detected.”, Toast.LENGTH_LONG).show(); } } Following will the modified content of AndroidManifest.xml file. Here we have added <receiver…/> tag to include our service: <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.tutorialspoint7.myapplication”> <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:supportsRtl=”true” android:theme=”@style/AppTheme”> <activity android:name=”.MainActivity”> <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> <receiver android:name=”MyReceiver”> <intent-filter> <action android:name=”com.tutorialspoint.CUSTOM_INTENT”> </action> </intent-filter> </receiver> </application> </manifest> Following will be the content of res/layout/activity_main.xml file to include a button to broadcast our custom intent − <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:id=”@+id/textView1″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Example of Broadcast” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:textSize=”30dp” /> <TextView android:id=”@+id/textView2″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point ” android:textColor=”#ff87ff09″ android:textSize=”30dp” android:layout_above=”@+id/imageButton” android:layout_centerHorizontal=”true” android:layout_marginBottom=”40dp” /> <ImageButton android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageButton” android:src=”@drawable/abc” android:layout_centerVertical=”true” android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/button2″ android:text=”Broadcast Intent” android:onClick=”broadcastIntent” android:layout_below=”@+id/imageButton” android:layout_centerHorizontal=”true” /> </RelativeLayout> Let”s try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment set-up. To run the app from Android studio, open one of your project”s activity files and click Run icon from the tool bar. Android Studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window − Now to broadcast our
Category: Android
Android – Internal Storage
Android – Internal Storage ”; Previous Next Android provides many kinds of storage for applications to store their data. These storage places are shared preferences, internal and external storage, SQLite storage, and storage via network connection. In this chapter we are going to look at the internal storage. Internal storage is the storage of the private data on the device memory. By default these files are private and are accessed by only your application and get deleted , when user delete your application. Writing file In order to use internal storage to write some data in the file, call the openFileOutput() method with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is given below − FileOutputStream fOut = openFileOutput(“file name here”,MODE_WORLD_READABLE); The method openFileOutput() returns an instance of FileOutputStream. So you receive it in the object of FileInputStream. After that you can call write method to write data on the file. Its syntax is given below − String str = “data”; fOut.write(str.getBytes()); fOut.close(); Reading file In order to read from the file you just created , call the openFileInput() method with the name of the file. It returns an instance of FileInputStream. Its syntax is given below − FileInputStream fin = openFileInput(file); After that, you can call read method to read one character at a time from the file and then you can print it. Its syntax is given below − int c; String temp=””; while( (c = fin.read()) != -1){ temp = temp + Character.toString((char)c); } //string temp contains all the data of the file. fin.close(); Apart from the the methods of write and close, there are other methods provided by the FileOutputStream class for better writing files. These methods are listed below − Sr.No Method & description 1 FileOutputStream(File file, boolean append) This method constructs a new FileOutputStream that writes to file. 2 getChannel() This method returns a write-only FileChannel that shares its position with this stream 3 getFD() This method returns the underlying file descriptor 4 write(byte[] buffer, int byteOffset, int byteCount) This method Writes count bytes from the byte array buffer starting at position offset to this stream Apart from the the methods of read and close, there are other methods provided by the FileInputStream class for better reading files. These methods are listed below − Sr.No Method & description 1 available() This method returns an estimated number of bytes that can be read or skipped without blocking for more input 2 getChannel() This method returns a read-only FileChannel that shares its position with this stream 3 getFD() This method returns the underlying file descriptor 4 read(byte[] buffer, int byteOffset, int byteCount) This method reads at most length bytes from this stream and stores them in the byte array b starting at offset Example Here is an example demonstrating the use of internal storage to store and read files. It creates a basic storage application that allows you to read and write from internal storage. To experiment with this example, you can run this on an actual device or in an emulator. Steps Description 1 You will use Android Studio IDE to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components 4 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.FileInputStream; import java.io.FileOutputStream; public class MainActivity extends Activity { Button b1,b2; TextView tv; EditText ed1; String data; private String file = “mydata”; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); b2=(Button)findViewById(R.id.button2); ed1=(EditText)findViewById(R.id.editText); tv=(TextView)findViewById(R.id.textView2); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { data=ed1.getText().toString(); try { FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE); fOut.write(data.getBytes()); fOut.close(); Toast.makeText(getBaseContext(),”file saved”,Toast.LENGTH_SHORT).show(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { FileInputStream fin = openFileInput(file); int c; String temp=””; while( (c = fin.read()) != -1){ temp = temp + Character.toString((char)c); } tv.setText(temp); Toast.makeText(getBaseContext(),”file read”,Toast.LENGTH_SHORT).show(); } catch(Exception e){ } } }); } } Following is the modified content of the xml res/layout/activity_main.xml. In the following code abc indicates the logo of tutorialspoint.com <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:text=”Internal storage” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textview” android:textSize=”35dp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35dp” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Save” android:id=”@+id/button” android:layout_alignParentBottom=”true” android:layout_alignLeft=”@+id/textView” android:layout_alignStart=”@+id/textView” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:hint=”Enter Text” android:focusable=”true” android:textColorHighlight=”#ff7eff15″ android:textColorHint=”#ffff25e6″ android:layout_below=”@+id/imageView” android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” android:layout_marginTop=”42dp” android:layout_alignLeft=”@+id/imageView” android:layout_alignStart=”@+id/imageView” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”load” android:id=”@+id/button2″ android:layout_alignTop=”@+id/button” android:layout_alignRight=”@+id/editText” android:layout_alignEnd=”@+id/editText” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Read” android:id=”@+id/textView2″ android:layout_below=”@+id/editText” android:layout_toLeftOf=”@+id/button2″ android:layout_toStartOf=”@+id/button2″ android:textColor=”#ff5bff1f” android:textSize=”25dp” /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name=”app_name”>My Application</string> </resources> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run our Storage application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window − Now what you need to do is to enter any text in the field. For example , i have entered some text. Press the save button. The following notification would appear in you AVD − Now when you press the load button, the application will read the file , and display the data. In case of our, following data would be returned
Android – Notifications
Android – Notifications ”; Previous Next A notification is a message you can display to the user outside of your application”s normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time. Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persistent which means alert flashes on the screen for a few seconds and then disappears. To see the details of the notification, you will have to select the icon which will display notification drawer having detail about the notification. While working with emulator with virtual device, you will have to click and drag down the status bar to expand it which will give you detail as follows. This will be just 64 dp tall and called normal view. Above expanded form can have a Big View which will have additional detail about the notification. You can add upto six additional lines in the notification. The following screen shot shows such notification. Create and Send Notifications You have simple way to create a notification. Follow the following steps in your application to create a notification − Step 1 – Create Notification Builder As a first step is to create a notification builder using NotificationCompat.Builder.build(). You will use Notification Builder to set various Notification properties like its small and large icons, title, priority etc. NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) Step 2 – Setting Notification Properties Once you have Builder object, you can set its Notification properties using Builder object as per your requirement. But this is mandatory to set at least following − A small icon, set by setSmallIcon() A title, set by setContentTitle() Detail text, set by setContentText() mBuilder.setSmallIcon(R.drawable.notification_icon); mBuilder.setContentTitle(“Notification Alert, Click Me!”); mBuilder.setContentText(“Hi, This is Android Notification Detail!”); You have plenty of optional properties which you can set for your notification. To learn more about them, see the reference documentation for NotificationCompat.Builder. Step 3 – Attach Actions This is an optional part and required if you want to attach an action with the notification. An action allows users to go directly from the notification to an Activity in your application, where they can look at one or more events or do further work. The action is defined by a PendingIntent containing an Intent that starts an Activity in your application. To associate the PendingIntent with a gesture, call the appropriate method of NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent(). A PendingIntent object helps you to perform an action on your applications behalf, often at a later time, without caring of whether or not your application is running. We take help of stack builder object which will contain an artificial back stack for the started Activity. This ensures that navigating backward from the Activity leads out of your application to the Home screen. Intent resultIntent = new Intent(this, ResultActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(ResultActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); Step 4 – Issue the notification Finally, you pass the Notification object to the system by calling NotificationManager.notify() to send your notification. Make sure you call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // notificationID allows you to update the notification later on. mNotificationManager.notify(notificationID, mBuilder.build()); The NotificationCompat.Builder Class The NotificationCompat.Builder class allows easier control over all the flags, as well as help constructing the typical notification layouts. Following are few important and most frequently used methods available as a part of NotificationCompat.Builder class. Sr.No. Constants & Description 1 Notification build() Combine all of the options that have been set and return a new Notification object. 2 NotificationCompat.Builder setAutoCancel (boolean autoCancel) Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel. 3 NotificationCompat.Builder setContent (RemoteViews views) Supply a custom RemoteViews to use instead of the standard one. 4 NotificationCompat.Builder setContentInfo (CharSequence info) Set the large text at the right-hand side of the notification. 5 NotificationCompat.Builder setContentIntent (PendingIntent intent) Supply a PendingIntent to send when the notification is clicked. 6 NotificationCompat.Builder setContentText (CharSequence text) Set the text (second row) of the notification, in a standard notification. 7 NotificationCompat.Builder setContentTitle (CharSequence title) Set the text (first row) of the notification, in a standard notification. 8 NotificationCompat.Builder setDefaults (int defaults) Set the default notification options that will be used. 9 NotificationCompat.Builder setLargeIcon (Bitmap icon) Set the large icon that is shown in the ticker and notification. 10 NotificationCompat.Builder setNumber (int number) Set the large number at the right-hand side of the notification. 11 NotificationCompat.Builder setOngoing (boolean ongoing) Set whether this is an ongoing notification. 12 NotificationCompat.Builder setSmallIcon (int icon) Set the small icon to use in the notification layouts. 13 NotificationCompat.Builder setStyle (NotificationCompat.Style style) Add a rich notification style to be applied at build time. 14 NotificationCompat.Builder setTicker (CharSequence tickerText) Set the text that is displayed in the status bar when the notification first arrives. 15 NotificationCompat.Builder setVibrate (long[] pattern) Set the vibration pattern to use. 16 NotificationCompat.Builder setWhen (long when) Set the time that the event occurred. Notifications in the panel are sorted by this time. Example Following example shows the functionality of a Android notification using a NotificationCompat.Builder Class which has been introduced in Android 4.1. Step Description 1 You will use Android studio IDE to create an Android application and name it as tutorialspoint under a package com.example.notificationdemo. 2 Modify src/MainActivity.java file and add the code to notify(“”), if user click on the button,it will call android notification
Android – Environment Setup
Android – Environment Setup ”; Previous Next You will be glad to know that you can start your Android application development on either of the following operating systems − Microsoft Windows XP or later version. Mac OS X 10.5.8 or later version with Intel chip. Linux including GNU C Library 2.7 or later. Second point is that all the required tools to develop Android applications are freely available and can be downloaded from the Web. Following is the list of software”s you will need before you start your Android application programming. Java JDK5 or later version Android Studio Here last two components are optional and if you are working on Windows machine then these components make your life easy while doing Java based application development. So let us have a look how to proceed to set required environment. Set-up Java Development Kit (JDK) You can download the latest version of Java JDK from Oracle”s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the JDK in C:jdk1.8.0_102, you would have to put the following line in your C:autoexec.bat file. set PATH=C:jdk1.8.0_102bin;%PATH% set JAVA_HOME=C:jdk1.8.0_102 Alternatively, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button. On Linux, if the SDK is installed in /usr/local/jdk1.8.0_102 and you use the C shell, you would put the following code into your .cshrc file. setenv PATH /usr/local/jdk1.8.0_102/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.8.0_102 Alternatively, if you use Android studio, then it will know automatically where you have installed your Java. Android IDEs There are so many sophisticated Technologies are available to develop android applications, the familiar technologies, which are predominantly using tools as follows Android Studio Eclipse IDE(Deprecated) Print Page Previous Next Advertisements ”;
Android – Content Providers
Android – Content Providers ”; Previous Next A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. A content provider can use different ways to store its data and the data can be stored in a database, in files, or even over a network. ContentProvider sometimes it is required to share data across applications. This is where content providers become very useful. Content providers let you centralize content in one place and have many different applications access it as needed. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete content using insert(), update(), delete(), and query() methods. In most cases this data is stored in an SQlite database. A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions. public class My Application extends ContentProvider { } Content URIs To query a content provider, you specify the query string in the form of a URI which has following format − <prefix>://<authority>/<data_type>/<id> Here is the detail of various parts of the URI − Sr.No Part & Description 1 prefix This is always set to content:// 2 authority This specifies the name of the content provider, for example contacts, browser etc. For third-party content providers, this could be the fully qualified name, such as com.tutorialspoint.statusprovider 3 data_type This indicates the type of data that this particular provider provides. For example, if you are getting all the contacts from the Contacts content provider, then the data path would be people and URI would look like thiscontent://contacts/people 4 id This specifies the specific record requested. For example, if you are looking for contact number 5 in the Contacts content provider then URI would look like this content://contacts/people/5. Create Content Provider This involves number of simple steps to create your own content provider. First of all you need to create a Content Provider class that extends the ContentProviderbaseclass. Second, you need to define your content provider URI address which will be used to access the content. Next you will need to create your own database to keep the content. Usually, Android uses SQLite database and framework needs to override onCreate() method which will use SQLite Open Helper method to create or open the provider”s database. When your application is launched, the onCreate() handler of each of its Content Providers is called on the main application thread. Next you will have to implement Content Provider queries to perform different database specific operations. Finally register your Content Provider in your activity file using <provider> tag. Here is the list of methods which you need to override in Content Provider class to have your Content Provider working − ContentProvider onCreate() This method is called when the provider is started. query() This method receives a request from a client. The result is returned as a Cursor object. insert()This method inserts a new record into the content provider. delete() This method deletes an existing record from the content provider. update() This method updates an existing record from the content provider. getType() This method returns the MIME type of the data at the given URI. Example This example will explain you how to create your own ContentProvider. So let”s follow the following steps to similar to what we followed while creating Hello World Example− Step Description 1 You will use Android StudioIDE to create an Android application and name it as My Application under a package com.example.MyApplication, with blank Activity. 2 Modify main activity file MainActivity.java to add two new methods onClickAddName() and onClickRetrieveStudents(). 3 Create a new java file called StudentsProvider.java under the package com.example.MyApplication to define your actual provider and associated methods. 4 Register your content provider in your AndroidManifest.xml file using <provider…/> tag 5 Modify the default content of res/layout/activity_main.xml file to include a small GUI to add students records. 6 No need to change string.xml.Android studio take care of string.xml file. 7 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity file src/com.example.MyApplication/MainActivity.java. This file can include each of the fundamental life cycle methods. We have added two new methods onClickAddName() and onClickRetrieveStudents() to handle user interaction with the application. package com.example.MyApplication; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.ContentValues; import android.content.CursorLoader; import android.database.Cursor; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onClickAddName(View view) { // Add a new student record ContentValues values = new ContentValues(); values.put(StudentsProvider.NAME, ((EditText)findViewById(R.id.editText2)).getText().toString()); values.put(StudentsProvider.GRADE, ((EditText)findViewById(R.id.editText3)).getText().toString()); Uri uri = getContentResolver().insert( StudentsProvider.CONTENT_URI, values); Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show(); } public void onClickRetrieveStudents(View view) { // Retrieve student records String URL = “content://com.example.MyApplication.StudentsProvider”; 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()); } } } Create new file StudentsProvider.java under com.example.MyApplication package and following is the content of src/com.example.MyApplication/StudentsProvider.java − package com.example.MyApplication; 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; public class StudentsProvider extends ContentProvider { static final String PROVIDER_NAME = “com.example.MyApplication.StudentsProvider”; static final String URL = “content://” + PROVIDER_NAME + “/students”; static final Uri CONTENT_URI = Uri.parse(URL); static final String _ID = “_id”; static final String NAME = “name”; static final String GRADE = “grade”; private static HashMap<String, String> STUDENTS_PROJECTION_MAP; static final int STUDENTS = 1; static final int STUDENT_ID = 2; static final UriMatcher uriMatcher; static{ uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, “students”, STUDENTS); uriMatcher.addURI(PROVIDER_NAME, “students/#”, STUDENT_ID); } /** * Database specific constant declarations */ private SQLiteDatabase db; static final String DATABASE_NAME = “College”; static final String STUDENTS_TABLE_NAME = “students”; static
Android – Resources
Android Resources Organizing & Accessing ”; Previous Next There are many more items which you use to build a good Android application. Apart from coding for the application, you take care of various other resources like static content that your code uses, such as bitmaps, colors, layout definitions, user interface strings, animation instructions, and more. These resources are always maintained separately in various sub-directories under res/ directory of the project. This tutorial will explain you how you can organize your application resources, specify alternative resources and access them in your applications. Organize resource in Android Studio MyProject/ app/ manifest/ AndroidManifest.xml java/ MyActivity.java res/ drawable/ icon.png layout/ activity_main.xml info.xml values/ strings.xml Sr.No. Directory & Resource Type 1 anim/ XML files that define property animations. They are saved in res/anim/ folder and accessed from the R.anim class. 2 color/ XML files that define a state list of colors. They are saved in res/color/ and accessed from the R.color class. 3 drawable/ Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps, state lists, shapes, animation drawable. They are saved in res/drawable/ and accessed from the R.drawable class. 4 layout/ XML files that define a user interface layout. They are saved in res/layout/ and accessed from the R.layout class. 5 menu/ XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu. They are saved in res/menu/ and accessed from the R.menu class. 6 raw/ Arbitrary files to save in their raw form. You need to call Resources.openRawResource() with the resource ID, which is R.raw.filename to open such raw files. 7 values/ XML files that contain simple values, such as strings, integers, and colors. For example, here are some filename conventions for resources you can create in this directory − arrays.xml for resource arrays, and accessed from the R.array class. integers.xml for resource integers, and accessed from the R.integer class. bools.xml for resource boolean, and accessed from the R.bool class. colors.xml for color values, and accessed from the R.color class. dimens.xml for dimension values, and accessed from the R.dimen class. strings.xml for string values, and accessed from the R.string class. styles.xml for styles, and accessed from the R.style class. 8 xml/ Arbitrary XML files that can be read at runtime by calling Resources.getXML(). You can save various configuration files here which will be used at run time. Alternative Resources Your application should provide alternative resources to support specific device configurations. For example, you should include alternative drawable resources ( i.e.images ) for different screen resolution and alternative string resources for different languages. At runtime, Android detects the current device configuration and loads the appropriate resources for your application. To specify configuration-specific alternatives for a set of resources, follow the following steps − Create a new directory in res/ named in the form <resources_name>-<config_qualifier>. Here resources_name will be any of the resources mentioned in the above table, like layout, drawable etc. The qualifier will specify an individual configuration for which these resources are to be used. You can check official documentation for a complete list of qualifiers for different type of resources. Save the respective alternative resources in this new directory. The resource files must be named exactly the same as the default resource files as shown in the below example, but these files will have content specific to the alternative. For example though image file name will be same but for high resolution screen, its resolution will be high. Below is an example which specifies images for a default screen and alternative images for high resolution screen. MyProject/ app/ manifest/ AndroidManifest.xml java/ MyActivity.java res/ drawable/ icon.png background.png drawable-hdpi/ icon.png background.png layout/ activity_main.xml info.xml values/ strings.xml Below is another example which specifies layout for a default language and alternative layout for Arabic language. MyProject/ app/ manifest/ AndroidManifest.xml java/ MyActivity.java res/ drawable/ icon.png background.png drawable-hdpi/ icon.png background.png layout/ activity_main.xml info.xml layout-ar/ main.xml values/ strings.xml Accessing Resources During your application development you will need to access defined resources either in your code, or in your layout XML files. Following section explains how to access your resources in both the scenarios − Accessing Resources in Code When your Android application is compiled, a R class gets generated, which contains resource IDs for all the resources available in your res/ directory. You can use R class to access that resource using sub-directory and resource name or directly resource ID. Example To access res/drawable/myimage.png and set an ImageView you will use following code − ImageView imageView = (ImageView) findViewById(R.id.myimageview); imageView.setImageResource(R.drawable.myimage); Here first line of the code make use of R.id.myimageview to get ImageView defined with id myimageview in a Layout file. Second line of code makes use of R.drawable.myimage to get an image with name myimage available in drawable sub-directory under /res. Example Consider next example where res/values/strings.xml has following definition − <?xml version=”1.0″ encoding=”utf-8″?> <resources> <string name=”hello”>Hello, World!</string> </resources> Now you can set the text on a TextView object with ID msg using a resource ID as follows − TextView msgTextView = (TextView) findViewById(R.id.msg); msgTextView.setText(R.string.hello); Example Consider a layout res/layout/activity_main.xml with the following definition − <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” > <TextView android:id=”@+id/text” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Hello, I am a TextView” /> <Button android:id=”@+id/button” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Hello, I am a Button” /> </LinearLayout> This application code will load this layout for an Activity, in the onCreate() method as follows − public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } Accessing Resources in XML Consider the following resource XML res/values/strings.xml file that includes a color resource and a string resource − <?xml version=”1.0″ encoding=”utf-8″?> <resources> <color name=”opaque_red”>#f00</color> <string name=”hello”>Hello!</string> </resources> Now you can use these resources in the following layout file to set the text color and text string as follows − <?xml version=”1.0″ encoding=”utf-8″?> <EditText xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:textColor=”@color/opaque_red” android:text=”@string/hello” /> Now if you will go through previous chapter once again where I have explained Hello World! example, and I”m sure you will have better understanding on all the concepts explained in this chapter.
Android – Home
Android Tutorial PDF Version Resources Job Search Discussion Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. This tutorial will teach you basic Android programming and will also take you through some advance concepts related to Android application development. Audience This tutorial has been prepared for the beginners to help them understand basic Android programming. After completing this tutorial you will find yourself at a moderate level of expertise in Android programming from where you can take yourself to next levels. Prerequisites Android programming is based on Java programming language so if you have basic understanding on Java programming then it will be a fun to learn Android application development. Print Page Previous Next Advertisements ”;
Android – Activities
Android – Activities ”; Previous Next An activity represents a single screen with a user interface just like window or frame of Java.Android activity is the subclass of ContextThemeWrapper class. If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function. Very similar way, Android system initiates its program with in an Activity starting with a call on onCreate() callback method. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity as shown in the below Activity life cycle diagram: (image courtesy : android.com ) The Activity class defines the following call backs i.e. events. You don”t need to implement all the callbacks methods. However, it”s important that you understand each one and implement those that ensure your app behaves the way users expect. Sr.No Callback & Description 1 onCreate() This is the first callback and called when the activity is first created. 2 onStart() This callback is called when the activity becomes visible to the user. 3 onResume() This is called when the user starts interacting with the application. 4 onPause() The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed. 5 onStop() This callback is called when the activity is no longer visible. 6 onDestroy() This callback is called before the activity is destroyed by the system. 7 onRestart() This callback is called when the activity restarts after stopping it. Example This example will take you through simple steps to show Android application activity life cycle. Follow the following steps to modify the Android application we created in Hello World Example chapter − Step Description 1 You will use Android studio to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter. 2 Modify main activity file MainActivity.java as explained below. Keep rest of the files unchanged. 3 Run the application to launch Android emulator and verify the result of the changes done in the application. Following is the content of the modified main activity file src/com.example.helloworld/MainActivity.java. This file includes each of the fundamental life cycle methods. The Log.d() method has been used to generate log messages − package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.util.Log; public class MainActivity extends Activity { String msg = “Android : “; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(msg, “The onCreate() event”); } /** Called when the activity is about to become visible. */ @Override protected void onStart() { super.onStart(); Log.d(msg, “The onStart() event”); } /** Called when the activity has become visible. */ @Override protected void onResume() { super.onResume(); Log.d(msg, “The onResume() event”); } /** Called when another activity is taking focus. */ @Override protected void onPause() { super.onPause(); Log.d(msg, “The onPause() event”); } /** Called when the activity is no longer visible. */ @Override protected void onStop() { super.onStop(); Log.d(msg, “The onStop() event”); } /** Called just before the activity is destroyed. */ @Override public void onDestroy() { super.onDestroy(); Log.d(msg, “The onDestroy() event”); } } An activity class loads all the UI component using the XML file available in res/layout folder of the project. Following statement loads UI components from res/layout/activity_main.xml file: setContentView(R.layout.activity_main); An application can have one or more activities without any restrictions. Every activity you define for your application must be declared in your AndroidManifest.xml file and the main activity for your app must be declared in the manifest with an <intent-filter> that includes the MAIN action and LAUNCHER category as follows: <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.tutorialspoint7.myapplication”> <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:supportsRtl=”true” android:theme=”@style/AppTheme”> <activity android:name=”.MainActivity”> <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app icon will not appear in the Home screen”s list of apps. Let”s try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display Emulator window and you should see following log messages in LogCat window in Android studio − 08-23 10:32:07.682 4480-4480/com.example.helloworld D/Android :: The onCreate() event 08-23 10:32:07.683 4480-4480/com.example.helloworld D/Android :: The onStart() event 08-23 10:32:07.685 4480-4480/com.example.helloworld D/Android :: The onResume() event Let us try to click lock screen button on the Android emulator and it will generate following events messages in LogCat window in android studio: 08-23 10:32:53.230 4480-4480/com.example.helloworld D/Android :: The onPause() event 08-23 10:32:53.294 4480-4480/com.example.helloworld D/Android :: The onStop() event Let us again try to unlock your screen on the Android emulator and it will generate following events messages in LogCat window in Android studio: 08-23 10:34:41.390 4480-4480/com.example.helloworld D/Android :: The onStart() event 08-23 10:34:41.392 4480-4480/com.example.helloworld D/Android :: The onResume() event Next, let us again try to click Back button on the Android emulator and it will generate following events messages in LogCat window in Android studio and this completes the Activity Life Cycle for an Android Application. 08-23 10:37:24.806 4480-4480/com.example.helloworld D/Android :: The onPause() event 08-23 10:37:25.668 4480-4480/com.example.helloworld D/Android :: The onStop() event 08-23 10:37:25.669 4480-4480/com.example.helloworld D/Android :: The onDestroy() event Print Page Previous Next Advertisements ”;
Android – Intents/Filters
Android – Intents and Filters ”; Previous Next An Android Intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service. The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed. For example, let”s assume that you have an Activity that needs to launch an email client and sends an email using your Android device. For this purpose, your Activity would send an ACTION_SEND along with appropriate chooser, to the Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send your email data. Intent email = new Intent(Intent.ACTION_SEND, Uri.parse(“mailto:”)); email.putExtra(Intent.EXTRA_EMAIL, recipients); email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString()); email.putExtra(Intent.EXTRA_TEXT, body.getText().toString()); startActivity(Intent.createChooser(email, “Choose an email client from…”)); Above syntax is calling startActivity method to start an email activity and result should be as shown below − For example, assume that you have an Activity that needs to open URL in a web browser on your Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the Android Intent Resolver to open given URL in the web browser. The Intent Resolver parses through a list of Activities and chooses the one that would best match your Intent, in this case, the Web Browser Activity. The Intent Resolver then passes your web page to the web browser and starts the Web Browser Activity. String q = “tutorialspoint”; Intent intent = new Intent(Intent.ACTION_WEB_SEARCH ); intent.putExtra(SearchManager.QUERY, q); startActivity(intent); Above example will search as tutorialspoint on android search engine and it gives the result of tutorialspoint in your an activity There are separate mechanisms for delivering intents to each type of component − activities, services, and broadcast receivers. Sr.No Method & Description 1 Context.startActivity() The Intent object is passed to this method to launch a new activity or get an existing activity to do something new. 2 Context.startService() The Intent object is passed to this method to initiate a service or deliver new instructions to an ongoing service. 3 Context.sendBroadcast() The Intent object is passed to this method to deliver the message to all interested broadcast receivers. Intent Objects An Intent object is a bundle of information which is used by the component that receives the intent as well as information used by the Android system. An Intent object can contain the following components based on what it is communicating or going to perform − Action This is mandatory part of the Intent object and is a string naming the action to be performed — or, in the case of broadcast intents, the action that took place and is being reported. The action largely determines how the rest of the intent object is structured . The Intent class defines a number of action constants corresponding to different intents. Here is a list of Android Intent Standard Actions The action in an Intent object can be set by the setAction() method and read by getAction(). Data Adds a data specification to an intent filter. The specification can be just a data type (the mimeType attribute), just a URI, or both a data type and a URI. A URI is specified by separate attributes for each of its parts − These attributes that specify the URL format are optional, but also mutually dependent − If a scheme is not specified for the intent filter, all the other URI attributes are ignored. If a host is not specified for the filter, the port attribute and all the path attributes are ignored. 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(). Some examples of action/data pairs are − Sr.No. Action/Data Pair & Description 1 ACTION_VIEW content://contacts/people/1 Display information about the person whose identifier is “1”. 2 ACTION_DIAL content://contacts/people/1 Display the phone dialer with the person filled in. 3 ACTION_VIEW tel:123 Display the phone dialer with the given number filled in. 4 ACTION_DIAL tel:123 Display the phone dialer with the given number filled in. 5 ACTION_EDIT content://contacts/people/1 Edit information about the person whose identifier is “1”. 6 ACTION_VIEW content://contacts/people/ Display a list of people, which the user can browse through. 7 ACTION_SET_WALLPAPER Show settings for choosing wallpaper 8 ACTION_SYNC It going to be synchronous the data,Constant Value is android.intent.action.SYNC 9 ACTION_SYSTEM_TUTORIAL It will start the platform-defined tutorial(Default tutorial or start up tutorial) 10 ACTION_TIMEZONE_CHANGED It intimates when time zone has changed 11 ACTION_UNINSTALL_PACKAGE It is used to run default uninstaller Category The category is an optional part of Intent object and it”s a string containing additional information about the kind of component that should handle the intent. The addCategory() method places a category in an Intent object, removeCategory() deletes a category previously added, and getCategories() gets the set of all categories currently in the object. Here is a list of Android Intent Standard Categories. You can check detail on Intent Filters in below section to understand how do we use categories to choose appropriate activity corresponding to an Intent. Extras This will be in key-value pairs for additional information that should be delivered to the component handling the intent. The extras can be set and read using the putExtras() and getExtras() methods respectively. Here is a list of Android Intent Standard Extra Data Flags These flags are optional part of Intent object and instruct the Android system how to launch an activity, and how to treat it after it”s launched etc. Sr.No Flags & Description 1 FLAG_ACTIVITY_CLEAR_TASK If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty
Android – Fragments
Android – Fragments ”; Previous Next A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-activity. Following are important points about fragment − A fragment has its own layout and its own behaviour with its own life cycle callbacks. You can add or remove fragments in an activity while the activity is running. You can combine multiple fragments in a single activity to build a multi-pane UI. A fragment can be used in multiple activities. Fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused, all the fragments available in the activity will also be stopped. A fragment can implement a behaviour that has no user interface component. Fragments were added to the Android API in Honeycomb version of Android which API version 11. You create fragments by extending Fragment class and You can insert a fragment into your activity layout by declaring the fragment in the activity”s layout file, as a <fragment> element. Prior to fragment introduction, we had a limitation because we can show only a single activity on the screen at one given point in time. So we were not able to divide device screen and control different parts separately. But with the introduction of fragment we got more flexibility and removed the limitation of having a single activity on the screen at a time. Now we can have a single activity but each activity can comprise of multiple fragments which will have their own layout, events and complete life cycle. Following is a typical example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design. The application can embed two fragments in Activity A, when running on a tablet-sized device. However, on a handset-sized screen, there”s not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment to read the article. Fragment Life Cycle Android fragments have their own life cycle very similar to an android activity. This section briefs different stages of its life cycle. Fragment lifecycle Here is the list of methods which you can to override in your fragment class − 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() The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed. onCreateView() The system calls this callback when it”s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment”s layout. You can return null if the fragment does not provide a UI. 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() 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()Fragment view will destroy after call this method onDestroy()onDestroy() called to do final clean up of the fragment”s state but Not guaranteed to be called by the Android platform. How to use Fragments? This involves number of simple steps to create Fragments. First of all decide how many fragments you want to use in an activity. For example let”s we want to use two fragments to handle landscape and portrait modes of the device. Next based on number of fragments, create classes which will extend the Fragment class. The Fragment class has above mentioned callback functions. You can override any of the functions based on your requirements. Corresponding to each fragment, you will need to create layout files in XML file. These files will have layout for the defined fragments. Finally modify activity file to define the actual logic of replacing fragments based on your requirement. Types of Fragments Basically fragments are divided as three stages as shown below. Single frame fragments − Single frame fragments are using for hand hold devices like mobiles, here we can show only one fragment as a view. List fragments − fragments having special list view is called as list fragment Fragments transaction − Using with fragment transaction. we can move one fragment to another fragment. Print Page Previous Next Advertisements ”;