You are on page 1of 68

Android Service

Android service is a component that is used to perform operations on the


background such as playing music, handle network transactions, interacting content
providers etc. It doesn't has any UI (user interface).

The service runs in the background indefinitely even if application is destroyed.

Moreover, service can be bounded by a component to perform interactivity and inter


process communication (IPC).

The android.app.Service is subclass of ContextWrapper class.

21.1MDifference between JDK, JRE, and JVM

Note: Android service is not a thread or separate process.

Life Cycle of Android Service


There can be two forms of a service.The lifecycle of service can follow two different
paths: started or bound.

1. Started
2. Bound

1) Started Service

A service is started when component (like activity) calls startService() method, now it


runs in the background indefinitely. It is stopped by stopService() method. The
service can stop itself by calling the stopSelf() method.

2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method.
The client can unbind the service by calling the unbindService() method.

The service cannot be stopped until all clients unbind the service.

Understanding Started and Bound Service by background music example

Suppose, I want to play music in the background, so call startService() method. But I
want to get information of the current song being played, I will bind the service that
provides information about the current song.

Android Service Example


Let's see the example of service in android that plays an audio in the background.
Audio will not be stopped even if you switch to another activity. To stop the audio,
you need to stop the service.
activity_main.xml

Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:

File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>  
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
4.     xmlns:tools="http://schemas.android.com/tools"  
5.     android:layout_width="match_parent"  
6.     android:layout_height="match_parent"  
7.     tools:context="example.javatpoint.com.androidservice.MainActivity">  
8.   
9.   
10.     <Button  
11.         android:id="@+id/buttonStart"  
12.         android:layout_width="wrap_content"  
13.         android:layout_height="wrap_content"  
14.         android:layout_alignParentTop="true"  
15.         android:layout_centerHorizontal="true"  
16.         android:layout_marginTop="74dp"  
17.         android:text="Start Service" />  
18.   
19.     <Button  
20.         android:id="@+id/buttonStop"  
21.         android:layout_width="wrap_content"  
22.         android:layout_height="wrap_content"  
23.         android:layout_centerHorizontal="true"  
24.         android:layout_centerVertical="true"  
25.         android:text="Stop Service" />  
26.   
27.     <Button  
28.         android:id="@+id/buttonNext"  
29.         android:layout_width="wrap_content"  
30.         android:layout_height="wrap_content"  
31.         android:layout_alignParentBottom="true"  
32.         android:layout_centerHorizontal="true"  
33.         android:layout_marginBottom="63dp"  
34.         android:text="Next Page" />  
35. </RelativeLayout>  

activity_next.xml

It is the layout file of next activity.

File: activity_next.xml

It contains only one textview displaying the message Next Page

1. <?xml version="1.0" encoding="utf-8"?>  
2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"  
3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
4.     xmlns:tools="http://schemas.android.com/tools"  
5.     android:layout_width="match_parent"  
6.     android:layout_height="match_parent"  
7.     tools:context="example.javatpoint.com.androidservice.NextPage">  
8.   
9.     <TextView  
10.         android:id="@+id/textView"  
11.         android:layout_width="wrap_content"  
12.         android:layout_height="wrap_content"  
13.         android:layout_marginEnd="8dp"  
14.         android:layout_marginStart="8dp"  
15.         android:layout_marginTop="200dp"  
16.         android:text="Next Page"  
17.         app:layout_constraintEnd_toEndOf="parent"  
18.         app:layout_constraintStart_toStartOf="parent"  
19.         app:layout_constraintTop_toTopOf="parent" />  
20. </android.support.constraint.ConstraintLayout>  

Service class

Now create the service implemenation class by inheriting the Service class and
overridding its callback methods.

1. File: MyService.java
2. package example.javatpoint.com.androidservice;  
3.   
4. import android.app.Service;  
5. import android.content.Intent;  
6. import android.media.MediaPlayer;  
7. import android.os.IBinder;  
8. import android.support.annotation.Nullable;  
9. import android.widget.Toast;  
10.   
11. public class MyService extends Service {  
12.     MediaPlayer myPlayer;  
13.     @Nullable  
14.     @Override  
15.     public IBinder onBind(Intent intent) {  
16.         return null;  
17.     }  
18.     @Override  
19.     public void onCreate() {  
20.         Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();  
21.   
22.         myPlayer = MediaPlayer.create(this, R.raw.sun);  
23.         myPlayer.setLooping(false); // Set looping  
24.     }  
25.     @Override  
26.     public void onStart(Intent intent, int startid) {  
27.         Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();  
28.         myPlayer.start();  
29.     }  
30.     @Override  
31.     public void onDestroy() {  
32.         Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();  
33.         myPlayer.stop();  
34.     }  
35. }  
36.

37. Activity class


38. Now create the MainActivity class to perform event handling. Here, we are
writing the code to start and stop service. Additionally, calling the second
activity on buttonNext.
39. File: MainActivity.java
40. package example.javatpoint.com.androidservice;  
41.   
42. import android.content.Intent;  
43. import android.support.v7.app.AppCompatActivity;  
44. import android.os.Bundle;  
45. import android.view.View;  
46. import android.widget.Button;  
47.   
48. public class MainActivity extends AppCompatActivity implements View.OnCl
ickListener{  
49.     Button buttonStart, buttonStop,buttonNext;  
50.     @Override  
51.     protected void onCreate(Bundle savedInstanceState) {  
52.         super.onCreate(savedInstanceState);  
53.         setContentView(R.layout.activity_main);  
54.   
55.         buttonStart = findViewById(R.id.buttonStart);  
56.         buttonStop = findViewById(R.id.buttonStop);  
57.         buttonNext =  findViewById(R.id.buttonNext);  
58.   
59.         buttonStart.setOnClickListener(this);  
60.         buttonStop.setOnClickListener(this);  
61.         buttonNext.setOnClickListener(this);  
62.   
63.   
64.     }  
65.     public void onClick(View src) {  
66.         switch (src.getId()) {  
67.             case R.id.buttonStart:  
68.   
69.                 startService(new Intent(this, MyService.class));  
70.                 break;  
71.             case R.id.buttonStop:  
72.                 stopService(new Intent(this, MyService.class));  
73.                 break;  
74.             case R.id.buttonNext:  
75.                 Intent intent=new Intent(this,NextPage.class);  
76.                 startActivity(intent);  
77.                 break;  
78.         }  
79.     }  
80. }  
NextPage class

Now, create another activity.

File: NextPage.java
package example.javatpoint.com.androidservice;  
  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
  
public class NextPage extends AppCompatActivity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_next);  
    }  
}  

Declare the Service in the AndroidManifest.xml file

Finally, declare the service in the manifest file.

File: AndroidManifest.xml

Let's see the complete AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="example.javatpoint.com.androidservice">  
  
    <application  
        android:allowBackup="true"  
        android:icon="@mipmap/ic_launcher"  
        android:label="@string/app_name"  
        android:roundIcon="@mipmap/ic_launcher_round"  
        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>  
        <activity android:name=".NextPage"></activity>  
        <service  
            android:name=".MyService"  
            android:enabled="true" />  
    </application>  
  
</manifest>  

Output:
 
 

Android - Shared Preferences


Android provides many ways of storing data of an application. One of this way is
called Shared Preferences. Shared Preferences allow you to save and retrieve data
in the form of key,value pair.
In order to use shared preferences, you have to call a method
getSharedPreferences() that returns a SharedPreference instance pointing to the
file that contains the values of preferences.
SharedPreferences sharedpreferences =
getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
The first parameter is the key and the second parameter is the MODE. Apart from
private there are other modes available that are listed below −

Sr.No Mode & description

1 MODE_APPEND
This will append the new preferences with the already existing preferences

2 MODE_ENABLE_WRITE_AHEAD_LOGGING
Database open flag. When it is set , it would enable write ahead logging by default

3 MODE_MULTI_PROCESS
This method will check for modification of preferences even if the
sharedpreference instance has already been loaded

4 MODE_PRIVATE
By setting this mode, the file can only be accessed using calling application

5 MODE_WORLD_READABLE
This mode allow other application to read the preferences

6 MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences

You can save something in the sharedpreferences by using


SharedPreferences.Editor class. You will call the edit method of SharedPreference
instance and will receive it in an editor object. Its syntax is −
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
Apart from the putString method , there are methods available in the editor class
that allows manipulation of data inside shared preferences. They are listed as
follows −

Sr. Mode & description


NO

1 apply()
It is an abstract method. It will commit your changes back from editor to the
sharedPreference object you are calling

2 clear()
It will remove all values from the editor

3 remove(String key)
It will remove the value whose key has been passed as a parameter

4 putLong(String key, long value)


It will save a long value in a preference editor

5 putInt(String key, int value)


It will save a integer value in a preference editor

6 putFloat(String key, float value)


It will save a float value in a preference editor

Example
This example demonstrates the use of the Shared Preferences. It display a screen
with some text fields, whose value are saved when the application is closed and
brought back when it is opened again.
To experiment with this example, you need to run this on an actual device on after
developing the application according to the steps below −

Steps Description

1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add progress code to display the spinning


progress dialog.

3 Modify res/layout/activity_main.xml file to add respective XML code.

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 MainActivity.java.


package com.example.sairamkrishna.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText ed1,ed2,ed3;
Button b1;

public static final String MyPREFERENCES = "MyPrefs" ;


public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";

SharedPreferences sharedpreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);

b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();

SharedPreferences.Editor editor =
sharedpreferences.edit();

editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();

Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show
();
}
});
}

Following is the content of the modified main activity


fileres/layout/activiy_main.xml.
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shared Preference "
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView2"
android:layout_marginTop="67dp"
android:hint="Name"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Pass" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Email" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_below="@+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />

</RelativeLayout>

Following is the content of the modified content of file res/values/strings.xml.


<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content default file AndroidManifest.xml.


<?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 your application. I assume you have connected your actual Android
Mobile device with your computer. To run the app from Android studio, open one of
your project's activity files and click Run   icon from the toolbar. Before starting
your application, Android studio will display following window to select an option
where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which
will display following screen −
Now just put in some text in the field. Like i put some random name and other
information and click on save button.
Now when you press save button, the text will be saved in the shared preferences.
Now press back button and exit the application. Now open it again and you will see
all the text you have written back in your application.
Android - Internal Storage
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.

getChannel()
2 This method returns a write-only FileChannel that shares its position with this
stream

getFD()
3
This method returns the underlying file descriptor

write(byte[] buffer, int byteOffset, int byteCount)


4 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


available()
1
This method returns an estimated number of bytes that can be read or skipped
without blocking for more input

getChannel()
2 This method returns a read-only FileChannel that shares its position with this
stream

getFD()
3
This method returns the underlying file descriptor

read(byte[] buffer, int byteOffset, int byteCount)


4 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 −
Note you can actually view this file by switching to DDMS tab. In DDMS , select file
explorer and navigate this path.
tools>android>android device Monitor
This has also been shown in the image below.
Android External Storage
Like internal storage, we are able to save or read data from the device external
memory such as sdcard. The FileInputStream and FileOutputStream classes are used
to read and write data into the file.

Example of reading and writing data in the android


external storage
activity_main.xml

Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the
activity_main.xml file will like this:

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.externalstorage.MainActivity">  
  
    <EditText  
        android:id="@+id/editText1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentRight="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginRight="20dp"  
        android:layout_marginTop="24dp"  
        android:ems="10" >  
  
        <requestFocus />  
    </EditText>  
  
    <EditText  
        android:id="@+id/editText2"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignRight="@+id/editText1"  
        android:layout_below="@+id/editText1"  
        android:layout_marginTop="24dp"  
        android:ems="10" />  
  
    <TextView  
        android:id="@+id/textView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignBaseline="@+id/editText1"  
        android:layout_alignBottom="@+id/editText1"  
        android:layout_alignParentLeft="true"  
        android:text="File Name:" />  
  
    <TextView  
        android:id="@+id/textView2"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignBaseline="@+id/editText2"  
        android:layout_alignBottom="@+id/editText2"  
        android:layout_alignParentLeft="true"  
        android:text="Data:" />  
  
    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignLeft="@+id/editText2"  
        android:layout_below="@+id/editText2"  
        android:layout_marginLeft="70dp"  
        android:layout_marginTop="16dp"  
        android:text="save" />  
  
    <Button  
        android:id="@+id/button2"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignBaseline="@+id/button1"  
        android:layout_alignBottom="@+id/button1"  
        android:layout_toRightOf="@+id/button1"  
        android:text="read" />  
</RelativeLayout>  

Provide permission for the external storage

You need to provide the WRITE_EXTERNAL_STORAGE permission.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
File: Activity_Manifest.xml

<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="example.javatpoint.com.externalstorage">  
    <uses-permission android:nam
e="android.permission.WRITE_EXTERNAL_STORAGE"/>  
    <application  
        android:allowBackup="true"  
        android:icon="@mipmap/ic_launcher"  
        android:label="@string/app_name"  
        android:roundIcon="@mipmap/ic_launcher_round"  
        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>  

Activity class

Let's write the code to write and read data from the android external storage.

Skip Ad

File: MainActivity.java

package example.javatpoint.com.externalstorage;  
  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.Toast;  
  
import java.io.BufferedReader;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.OutputStreamWriter;  
  
public class MainActivity extends AppCompatActivity {  
    EditText editTextFileName,editTextData;  
    Button saveButton,readButton;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        editTextFileName=findViewById(R.id.editText1);  
        editTextData=findViewById(R.id.editText2);  
        saveButton=findViewById(R.id.button1);  
        readButton=findViewById(R.id.button2);  
  
        //Performing action on save button  
        saveButton.setOnClickListener(new View.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).sh
ow();  
                } catch (FileNotFoundException e) {e.printStackTrace();}  
                catch (IOException e) {e.printStackTrace();}  
            }  
        });  
  
        //Performing action on Read Button  
        readButton.setOnClickListener(new View.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();  
            }  
        });  
    }  
}  
 
Android - Content Providers
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://

authority

2 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

data_type

3 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

id

4 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 final int DATABASE_VERSION = 1;
static final String CREATE_DB_TABLE =
" CREATE TABLE " + STUDENTS_TABLE_NAME +
" (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
" name TEXT NOT NULL, " +
" grade TEXT NOT NULL);";

/**
* 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) {
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 boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);

/**
* Create a write able database which will trigger its
* creation if it doesn't already exist.
*/

db = dbHelper.getWritableDatabase();
return (db == null)? false:true;
}

@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
public Cursor query(Uri uri, String[] projection,
String selection,String[] selectionArgs, String sortOrder)
{
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(STUDENTS_TABLE_NAME);

switch (uriMatcher.match(uri)) {
case STUDENTS:
qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
break;

case STUDENT_ID:
qb.appendWhere( _ID + "=" +
uri.getPathSegments().get(1));
break;

default:
}

if (sortOrder == null || sortOrder == ""){


/**
* By default sort on student names
*/
sortOrder = NAME;
}

Cursor c = qb.query(db, projection, selection,


selectionArgs,null, null, sortOrder);
/**
* register to watch a content URI for changes
*/
c.setNotificationUri(getContext().getContentResolver(),
uri);
return c;
}

@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 int update(Uri uri, ContentValues values,
String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case STUDENTS:
count = db.update(STUDENTS_TABLE_NAME, values,
selection, selectionArgs);
break;

case STUDENT_ID:
count = db.update(STUDENTS_TABLE_NAME, values,
_ID + " = " + uri.getPathSegments().get(1) +
(!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);
}
}
}

Following will the modified content of AndroidManifest.xml file. Here we have added


<provider.../> tag to include our content provider:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.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>

<provider android:name="StudentsProvider"

android:authorities="com.example.MyApplication.StudentsProvider"/
>
</application>
</manifest>

Following will be the content of res/layout/activity_main.xml file−


<?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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.MyApplication.MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Content provider"
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_below="@+id/textView1"
android:layout_centerHorizontal="true" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Add Name"
android:layout_below="@+id/editText3"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:onClick="onClickAddName"/>

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_alignTop="@+id/editText"
android:layout_alignLeft="@+id/textView1"
android:layout_alignStart="@+id/textView1"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1"
android:hint="Name"
android:textColorHint="@android:color/holo_blue_light" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText2"
android:layout_alignStart="@+id/editText2"
android:layout_alignRight="@+id/editText2"
android:layout_alignEnd="@+id/editText2"
android:hint="Grade"
android:textColorHint="@android:color/holo_blue_bright" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retrive student"
android:id="@+id/button"
android:layout_below="@+id/button2"
android:layout_alignRight="@+id/editText3"
android:layout_alignEnd="@+id/editText3"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"
android:onClick="onClickRetrieveStudents"/>
</RelativeLayout>

Make sure you have following content of res/values/strings.xml file:


<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
</resources>;

Let's try to run our modified My Application application we just created. I assume


you had created your AVD while doing environment set-up. To run the app from
Android Studio IDE, 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, be patience because it may take sometime based on your computer speed

Now let's enter student Name and Grade and finally click on Add Name button, this
will add student record in the database and will flash a message at the bottom
showing ContentProvider URI along with record number added in the database.
This operation makes use of our insert() method. Let's repeat this process to add
few more students in the database of our content provider.
Once you are done with adding records in the database, now its time to ask
ContentProvider to give us those records back, so let's click Retrieve
Students button which will fetch and display all the records one by one which is as
per our the implementation of our query() method.
You can write activities against update and delete operations by providing callback
functions in MainActivity.java file and then modify user interface to have buttons
for update and deleted operations in the same way as we have done for add and
read operations.
This way you can use existing Content Provider like Address Book or you can use
Content Provider concept in developing nice database oriented applications where
you can perform all sort of database operations like read, write, update and delete
as explained above in the example
Android Notification
Android Notification provides short, timely information about the action happened in
the application, even it is not running. The notification displays the icon, title and
some amount of the content text.

Set Android Notification Properties


The properties of Android notification are set
using NotificationCompat.Builder object. Some of the notification properties are
mention below:

o setSmallIcon(): It sets the icon of notification.


o setContentTitle(): It is used to set the title of notification.
o setContentText(): It is used to set the text message.
o setAutoCancel(): It sets the cancelable property of notification.
o setPriority(): It sets the priority of notification.

Android Notification Example


In this example, we will create a notification message which will launch another
activity after clicking on it.

activity_main.xml
Add the following code in an activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>  
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/
apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.androidnotification.MainActivity">  
  
    <TextView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="ANDROID NOTIFICATION"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintLeft_toLeftOf="parent"  
        app:layout_constraintRight_toRightOf="parent"  
        app:layout_constraintTop_toTopOf="parent"  
        app:layout_constraintVertical_bias="0.091"  
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>  
  
    <Button  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:id="@+id/button"  
        android:layout_marginBottom="112dp"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:text="Notify"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent" />  
  
</android.support.constraint.ConstraintLayout>  

Create an activity named as activity_notification_view.xml and add the following


code. This activity will be launched on clicking the notification. TextView is used to
display the notification message.

activity_notification_view.xml
<?xml version="1.0" encoding="utf-8"?>  
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/
apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.androidnotification.NotificationView">  
  
    <TextView  
        android:id="@+id/textView2"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:gravity="center"  
        android:text="your detail of notification..."  
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />  
  
    <TextView  
        android:id="@+id/textView"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_marginBottom="8dp"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:layout_marginTop="8dp"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintHorizontal_bias="0.096"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toBottomOf="@+id/textView2"  
        app:layout_constraintVertical_bias="0.206"  
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>  
  
</android.support.constraint.ConstraintLayout>  

MainActivity.java
In the MainActivity.java class adds the following code. In this class, clicking the
button calls the addNotification() method where we implement the
NotificationCompat.Builder object to set the notification properties. The
NotificationManager.notify() method is used to display the notification. The Intent
class is used to call another activity (NotificationView.java) on taping the notification.

package example.javatpoint.com.androidnotification;  
  
import android.app.NotificationManager;  
import android.app.PendingIntent;  
import android.content.Context;  
import android.content.Intent;  
import android.support.v4.app.NotificationCompat;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  
  
public class MainActivity extends AppCompatActivity {  
    Button button;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        button = findViewById(R.id.button);  
        button.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                addNotification();  
            }  
        });  
    }  
  
    private void addNotification() {  
        NotificationCompat.Builder builder =  
                new NotificationCompat.Builder(this)  
                        .setSmallIcon(R.drawable.messageicon) //set icon for notification  
                        .setContentTitle("Notifications Example") //set title of notification  
                        .setContentText("This is a notification message")//this is notification message  
                        .setAutoCancel(true) // makes auto cancel of notification  
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT); //set priority of notification  
  
  
        Intent notificationIntent = new Intent(this, NotificationView.class);  
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
        //notification message will get at NotificationView  
        notificationIntent.putExtra("message", "This is a notification message");  
  
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,  
                PendingIntent.FLAG_UPDATE_CURRENT);  
        builder.setContentIntent(pendingIntent);  
  
        // Add as notification  
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFIC
ATION_SERVICE);  
        manager.notify(0, builder.build());  
    }  
}  

NotificationView.java
The NotificationView.java class receives the notification message and is displayed
in TextView. This class is invoked while taping the notification.

package example.javatpoint.com.androidnotification;  
  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.widget.TextView;  
import android.widget.Toast;  
  
public class NotificationView extends AppCompatActivity {  
    TextView textView;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_notification_view);  
        textView = findViewById(R.id.textView);  
        //getting the notification message  
        String message=getIntent().getStringExtra("message");  
        textView.setText(message);  
    }  
}  

strings.xml
<resources>  
    <string name="app_name">AndroidNotification</string>  
    <string name="notification_activity">NotificationView</string>  
</resources>  

AndroidManifest.xml
Add the following code in AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="example.javatpoint.com.androidnotification">  
  
    <application  
        android:allowBackup="true"  
        android:icon="@mipmap/ic_launcher"  
        android:label="@string/app_name"  
        android:roundIcon="@mipmap/ic_launcher_round"  
        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>  
        <activity android:name=".NotificationView"  
            android:label="@string/notification_activity"  
            android:parentActivityName=".MainActivity">  
            <meta-data  
                android:name="android.support.PARENT_ACTIVITY"  
                android:value=".MainActivity"/>  
        </activity>  
    </application>  
  
</manifest>  

Output:
   

 
Playing Audio / Media Player

Playing Vedio/ Vedio view

Android AlarmManager
Android AlarmManager allows you to access system alarm.

By the help of Android AlarmManager in android, you can schedule your application


to run at a specific time in the future. It works whether your phone is running or not.

The Android AlarmManager holds a CPU wake lock that provides guarantee not to
sleep the phone until broadcast is handled.

Android AlarmManager Example


Let's see a simple AlarmManager example that runs after a specific time provided by

activity_main.xml

You need to drag only a edittext and a button as given below.

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.alarmmanager.MainActivity">  
  
    <Button  
        android:id="@+id/button"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="Start"  
        android:layout_alignParentBottom="true"  
        android:layout_centerHorizontal="true"  
        android:layout_marginBottom="103dp" />  
  
    <EditText  
        android:id="@+id/time"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentTop="true"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="22dp"  
        android:ems="10" />  
</RelativeLayout>  

Activity class

The activity class starts the alarm service when user clicks on the button.

File: MainActivity.java

package example.javatpoint.com.alarmmanager;  
  
import android.app.AlarmManager;  
import android.app.PendingIntent;  
import android.content.Intent;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.Toast;  
  
public class MainActivity extends AppCompatActivity {  
    Button start;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        start= findViewById(R.id.button);  
  
        start.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                startAlert();  
            }  
        });  
    }  
  
    public void startAlert(){  
        EditText text = findViewById(R.id.time);  
        int i = Integer.parseInt(text.getText().toString());  
        Intent intent = new Intent(this, MyBroadcastReceiver.class);  
        PendingIntent pendingIntent = PendingIntent.getBroadcast(  
                this.getApplicationContext(), 234324243, intent, 0);  
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVIC
E);  
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()  
                + (i * 1000), pendingIntent);  
        Toast.makeText(this, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show();  
    }  
}  

Let's create BroadcastReceiver class that starts alarm.

File: MyBroadcastReceiver.java

package example.javatpoint.com.alarmmanager;  
  
import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.media.MediaPlayer;  
import android.widget.Toast;  
  
public class MyBroadcastReceiver extends BroadcastReceiver {  
    MediaPlayer mp;  
    @Override  
    public void onReceive(Context context, Intent intent) {  
        mp=MediaPlayer.create(context, R.raw.alarm);  
        mp.start();  
        Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();  
    }  
}  

File: AndroidManifest.xml

You need to provide a receiver entry in AndroidManifest.xml file.

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

Let's see the full code of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="example.javatpoint.com.alarmmanager">  
  
    <application  
        android:allowBackup="true"  
        android:icon="@mipmap/ic_launcher"  
        android:label="@string/app_name"  
        android:roundIcon="@mipmap/ic_launcher_round"  
        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="MyBroadcastReceiver" >  
        </receiver>  
    </application>  
  
</manifest>  

Output:
   
GalleryView in Android with Example
 Last Updated : 13 Jul, 2021
In Android, Gallery is a view that can show items in a center locked, horizontal
scrolling list, and hence the user can able to select a view, and then the user selected
view will be shown in the center of the Horizontal list. “N” number of items can be
added by using the Adapter. The adapter is a bridging component between UI
component and data source(It can be an array of items defined in java code or from a
database). The items given in the adapter will be shown in the gallery in the example.
Important Point: Gallery class was deprecated in API level 16. Instead  other
horizontally scrolling widgets are HorizontalScrollView and ViewPager from the
support library are available.
Want a more fast-paced & competitive environment to learn the fundamentals of
Android?

Click here to head to a guide uniquely curated by our experts with the aim to make
you industry ready in no time!
Way to define a Gallery tag
 XML

<!-- By using android:spacing we can give spacing between images

     android:animationDuration="3000" -> for animation running -->

<Gallery

  android:id="@+id/languagesGallery"

  android:layout_width="match_parent"

  android:layout_height="wrap_content"

  android:layout_marginTop="100dp"

  android:unselectedAlpha="50"

  android:spacing="5dp"

  android:animationDuration="2000"

  android:padding="10dp" />

 
 

Important methods of the GalleryView in android


Methods Description

setAnimationDuration(int) To set the duration for how long a transition animation


should run 
(in milliseconds) whenever there is change in layout. 
Methods Description

This can be set in xml also via


android:animationDuration=”3000″

To set the spacing between items in a Gallery. This can be


set in xml 
setSpacing(int) also via android:spacing=”5dp”

To set the alpha on the items that are not selected. This can
be set in xml

setUnselectedAlpha(float) also via android:unselectedAlpha=”0.25″

 
Let us see the implementation of important methods:
 

 Java

// get the reference of Gallery first

Gallery simpleGallery = (Gallery) findViewById(R.id.languagesGallery);

// set 3000 milliseconds for animation duration between each items of Gallery

// xml equivalent -> android:animationDuration="2000"

simpleGallery.setAnimationDuration(2000);

 
// set space between the items of Gallery

// xml equivalent -> android:spacing="15dp"

simpleGallery.setSpacing(15);

// set 0.25 value for the alpha of unselected items of Gallery

// xml equivalent -> android:unselectedAlpha="0.25"

simpleGallery.setUnselectedAlpha(0.25f);

Attributes of GalleryView
Attributes Description

id To uniquely identify a Gallery

To set the padding from the left, right, the top or bottom side of a
padding Gallery.

paddingRight To set the padding from the right side of a Gallery.

paddingLeft To set the padding from the left side of a Gallery.

paddingTop To set the padding from the top side of a Gallery.

paddingBottom To set the padding from the bottom side of a Gallery.

padding To set the padding from all the sides of a Gallery.


Attributes Description

To set the background of a Gallery. For background, either we can


set colors (using colors.xml) or images which are kept under
drawable folder
Via java code also, we can set the background color in the below
way

simpleGallery.setBackgroundColor(Color.GFGGreencolor); // set
background the desired color

To set the duration for how long a transition animation should run
(in milliseconds)
Via java, 
animationDuration simpleGallery.setAnimationDuration(<No of milliseconds>); 

To set the spacing between items in a Gallery. 


Via java,
simpleGallery.setSpacing(10);  // We can set spacing between
spacing items as per our requirement

To set the alpha on the items that are not selected.


Via java,
unselectedAlpha simpleGallery.setUnselectedAlpha(0.25f)

Example

A sample GIF is given below to get an idea about what we are going to do in


this article. Note that we are going to implement this project using the Java language. 

You might also like