[go: up one dir, main page]

0% found this document useful (0 votes)
8 views60 pages

Chapter 5

The document discusses the use of Intents in Android for communication between application components, detailing explicit and implicit intents. It includes examples of how to implement these intents in Java and XML, as well as the activity lifecycle and broadcast receivers. Additionally, it covers the MediaPlayer class for playing audio and video files in Android applications.

Uploaded by

bitmasters52
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views60 pages

Chapter 5

The document discusses the use of Intents in Android for communication between application components, detailing explicit and implicit intents. It includes examples of how to implement these intents in Java and XML, as well as the activity lifecycle and broadcast receivers. Additionally, it covers the MediaPlayer class for playing audio and video files in Android applications.

Uploaded by

bitmasters52
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 60

Chapter 05

Activity and Multimedia with database

Intent
Android uses Intent for communicating between the components of an Application and also from one
application to another application.
Intent are the objects which is used in android for passing the information among Activities in an
Application and from one app to another also.
Intent are used for communicating between the Application components and it also provides the
connectivity between two apps.
Intent are of two types:
 Explicit Intent
 Implicit Intent

Explicit Intent:
 Explicit Intents are used to connect the application internally.
 In Explicit we use the name of component which will be affected by Intent.

If we know class name then we can navigate the app from One Activity to another activity using Intent.

Explicit Intent work internally within an application to perform navigation and data transfer.

Intent in = new Intent(getApplicationContext(), SecondActivity.class);


startActivity(in);

Implicit Intent:
 In Implicit Intents we do need to specify the name of the component. We just specify the
Action which has to be performed and further this action is handled by the component of
another application.
 The basic example of implicit Intent is to open any web page

Intent intentObj = new Intent(Intent.ACTION_VIEW);


intentObj.setData(Uri.parse("https://www.google.com"));
startActivity(intentObj);

activity_main.xml

<RelativeLayout
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explicit Intent Example"
android:id="@+id/b1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Implicit Intent Example"
android:id="@+id/b2"/>
</RelativeLayout>

activity_second.xml

<RelativeLayout
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Second Activity"
android:id="@+id/textView" />
</RelativeLayout>

public class MainActivity extends AppCompatActivity


{
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.b1);
B2 = (Button) findViewById(R.id.b2);

B1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Intent in = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(in);
}
});

B2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent intent = new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
}
});
}}

SecondActivity.java

public class SecondActivity extends AppCompatActivity {


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

Toast.makeText(getApplicationContext(), "We are moved to second


Activity",Toast.LENGTH_LONG).show();
}}

Intent Filter are the components which decide the behavior of an intent.Intent filters specify the type
of intents that an Activity, service or Broadcast receiver can respond to. It declares the functionality
of its parent component. The code of Intent Filter is used inside AndroidManifest.xml file for an
activity. You can see it: open manifests folder >> open AndroidManifest.xml file

Example 2:
<?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"
android:padding="10dp"
android:id="@+id/f1"
tools:context=".login">

<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Intent"
android:textSize="20dp"
android:gravity="center"/>

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_marginTop="35dp"
android:text="Next page" />

<EditText
android:id="@+id/url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="41dp"
android:hint="Enter URL" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="167dp"
android:text="Google" />

</RelativeLayout>

Java File
package com.example.ifcdiv;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class login extends AppCompatActivity {


Button b1,b2;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
b1=findViewById(R.id.button1);
editText=findViewById(R.id.url);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new Intent(getApplicationContext(),secondPage.class);
startActivity(in);

}
});

b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str=editText.getText().toString();
Intent in=new Intent(Intent.ACTION_VIEW);
in.setData(Uri.parse("https://"+str));
startActivity(in);
}
});

}
}

Example:

<?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"
android:padding="40dp"
tools:context=".MainActivity">
<Button
android:id="@+id/b1"
android:text="Dialpad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>

Java File

package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


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

b=findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_DIAL);
startActivity(i);

}
});
}
}

Example:

<?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"
android:padding="40dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/e1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textAlignment="center"/>
<Button
android:id="@+id/b1"
android:text="Factorial"
android:layout_below="@+id/e1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/>
</RelativeLayout>

Java File

package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


EditText e;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=findViewById(R.id.b1);
e=findViewById(R.id.e1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str=String.valueOf(e.getText());
Intent i=new Intent(MainActivity.this,login.class);
i.putExtra("msg_key",str);
startActivity(i);
}
});
}
}

<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"
android:padding="10dp"
android:id="@+id/f1"
tools:context=".login">

<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textAlignment="center"
android:textSize="100px"
android:textStyle="bold"/>
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/t1"
android:layout_centerHorizontal="true"
android:text="BACK"/>
</RelativeLayout>

Java File

package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class login extends AppCompatActivity {


TextView t;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
t=findViewById(R.id.t1);
Intent a=getIntent();
String str=a.getStringExtra("msg_key");
int num=Integer.parseInt(str);
int fact=1;
for(int i=1;i<=num;i++)
{
fact=fact*i;
}
String s=String.valueOf(fact);
t.setText(s);

b=findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(login.this,MainActivity.class);
startActivity(i);
}
});
}
}

Activity Lifecycle

onCreate()
This is the first callback and called when the activity is first created.
onStart()
This callback is called when the activity becomes visible to the user.
onResume()
This is called when the user starts interacting with the application.
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.
onStop()
This callback is called when the activity is no longer visible.
onDestroy()
This callback is called before the activity is destroyed by the system.
onRestart()
This callback is called when the activity restarts after stopping it.

Example:

When you open the app it will go through below states:

onCreate() –> onStart() –> onResume()

When you press the back button and exit the app

onPaused() — > onStop() –> onDestory()

When you press the home button

onPaused() –> onStop()

After pressing the home button, again when you open the app from a recent task list

onRestart() –> onStart() –> onResume()

After dismissing the dialog or back button from the dialog

onResume()

If a phone is ringing and user is using the app

onPause() –> onResume()

After the call ends

onResume()

When your phone screen is off

onPaused() –> onStop()

When your phone screen is turned back on

onRestart() –> onStart() –> onResume()


Example:
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Life cycle","Create method");
}

@Override
protected void onStart() {
super.onStart();
Log.d("Life cycle","start method");
}

@Override
protected void onResume() {
super.onResume();
Log.d("Life cycle","Resume method");
}
@Override
protected void onPause(){
super.onPause();
Log.d("Life cycle","pause method");
}
@Override
protected void onStop(){
super.onStop();
Log.d("Life cycle","stop method");
}
@Override
public void onDestroy(){
super.onDestroy();
Log.d("Life cycle","destroy method");
}
@Override
public void onRestart(){
super.onResort();
Log.d("Life cycle","Restart method");
}

Broadcast Lifecycle
 A broadcast receiver is a dormant component of the Android system.
 The Broadcast Receiver’s job is to pass a notification to the user, in case a specific event
occurs.
 Using a Broadcast Receiver, applications can register for a particular event.
 Once the event occurs, the system will notify all the registered applications.

Example :
Steps:
Right click on package and select new
1) Select Other option

2) Select BroadcastReceiver

3) Give name to file

Example:
MyReceiver.java

package com.example.ifcdiv;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

String actionstring=intent.getAction();
Toast.makeText(context,actionstring,Toast.LENGTH_LONG).show();
}
}

MainActivity.java

package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {


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

@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
this.registerReceiver(myReceiver,intentFilter);

@Override
protected void onStop() {
super.onStop();
this.unregisterReceiver(myReceiver);
}
}

Play Audio and Video


Play Audio
 We can play and control the audio files in android by the help of MediaPlayer class.
 Android is providing MediaPlayer class to access built-in mediaplayer services like playing
audio,video e.t.c.
 In order to use MediaPlayer, we have to call a static Method create() of this class. This method
returns an instance of MediaPlayer class.
Its syntax is as follows −

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);


 The second parameter is the name of the song that you want to play.
 You have to make a new folder under your project with name raw and place the music file
into it.
 Once you have created the Mediaplayer object you can call some methods to start or stop the
music.
These methods are listed below.
mediaPlayer.start();
mediaPlayer.pause();
 On call to start() method, the music will start playing from the beginning.
 If this method is called again after the pause() method, the music would start playing from
where it is left and not from the beginning.
 In order to start music from the beginning, you have to call reset() method. Its syntax is given
below.

mediaPlayer.reset();

Example
<?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"
android:padding="40dp"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView
android:id="@+id/headingText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="MEDIA PLAYER"
android:textSize="18sp"
android:textStyle="bold" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/headingText"
android:layout_marginTop="16dp"
android:gravity="center_horizontal">

<Button
android:id="@+id/stopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="STOP"
android:textColor="@android:color/white" />

<Button
android:id="@+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="PLAY"
android:textColor="@android:color/white" />

<Button
android:id="@+id/pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PAUSE"
android:textColor="@android:color/white" />

</LinearLayout>
</RelativeLayout>

File: MainActivity.java
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


Button start,pause,stop;
MediaPlayer mp=new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.playButton);
pause=(Button)findViewById(R.id.pauseButton);
stop=(Button)findViewById(R.id.stopButton);

mp = MediaPlayer.create(this,R.raw.sheeran);

start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
mp.stop();
mp.prepare();
}catch (IOException e)
{
e.printStackTrace();
}
}
});

}
}

Android Video Player

By the help of MediaController and VideoView classes, we can play the video files in android.

MediaController class

The android.widget.MediaController is a view that contains media controls like play/pause, previous,
next, fast-forward, rewind etc.

VideoView class

The android.widget.VideoView class provides methods to play and control the video player.

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=".MainActivity">

<VideoView
android:id="@+id/videoView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="0dp"
android:layout_marginBottom="0dp"/>
</RelativeLayout>

File: MainActivity.java

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView = (VideoView) findViewById(R.id.videoView);
videoView.setVideoPath("android.resource://"+getPackageName()+ "/" + R.raw.vid);
MediaController mediaController = new MediaController( this);
videoView.setMediaController(mediaController);
videoView.start();
}
}

VIDEO Capture (for reference)


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=".MainActivity">

<TextView
android:id="@+id/t1"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="150px"
android:text="Video Capturing"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open"
android:id="@+id/btn"
android:layout_below="@id/t1"
android:layout_centerHorizontal="true"/>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_below="@+id/btn"
>
<VideoView
android:layout_width="match_parent"
android:layout_height="400dp"
android:gravity="bottom"
android:layout_gravity="center_horizontal"
android:id="@+id/vv"
/>

</FrameLayout>
</RelativeLayout>

MainActivity.java
package com.example.myapplication;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity


{
Button btn;
VideoView vv;
int REQ=0;

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

btn = findViewById(R.id.btn);
vv = findViewById(R.id.vv);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(i,REQ);

}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode ==REQ) {
Uri videoUri = intent.getData();
vv.setVideoURI(videoUri);
vv.start();
}
}

Text to speech

 Android allows you convert your text into voice.


 Not only you can convert it but it also allows you to speak text in variety of different
languages.
 Android provides TextToSpeech class for this purpose. In order to use this class, you need to
instantiate an object of this class and also specify the initListener.
Its syntax is given below −
ttobj=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override

public void onInit(int status) {

}});

Language can be set by calling setLanguage() method.

ttobj.setLanguage(Locale.UK);

Example:
public class MainActivity extends Activity {
TextToSpeech t1;
EditText ed1;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
b1=(Button)findViewById(R.id.button);
t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.UK);
}
}
});

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = ed1.getText().toString();
t1.speak(str, TextToSpeech.QUEUE_FLUSH, null);
}
});
}

public void onPause(){


if(t1 !=null){
t1.stop();
t1.shutdown();
}
super.onPause();
}
}

Service
Features of Service
 A service is a component that runs in the background to perform long-running operations without
needing to interact with the user.
 A service is simply a component that can run in the background, even when the user is not
interacting with your application.

Android- Services Life cycle


 A service is a component that runs in the background to perform long-running operations without
needing to interact with the user.
 Android Services are the application components that run in the background. We can understand it as a
process that doesn’t need any direct user interaction.
 As they perform long-running processes without user intervention, they have no User Interface. They
can be connected to other components and do inter-process communication (IPC).
Android Services life cycle can have two forms of services. The lifecycle of a service follows two different
paths, namely:
 Started Service
 Bound Service

1. Started Service

A service becomes started only when an application component calls startService(). It performs a single
operation and doesn’t return any result to the caller. Once this service starts, it runs in the background
even if the component that created it destroys. This service can be stopped only in one of the two cases:

 By using the stopService() method.


 By stopping itself using the stopSelf() method.
2. Bound Service

A service is bound only if an application component binds to it using bindService(). It gives a client-
server relation that lets the components interact with the service. The components can send requests to
services and get results.

The onBind() is called when another Thread registers to connect to the Service so that they can
communicate.
1. onStartCommand()

The system calls this method whenever a component, say an activity requests ‘start’ to a service,
using startService().

Once we use this method it’s our duty to stop the service using stopService() or stopSelf().

2. onBind()

This is invoked when a component wants to bind with the service by alling bindService(). In this, we
must provide an interface for clients to communicate with the service. For interprocess communication,
we use the IBinder object.

It is a must to implement this method. If in case binding is not required, we should return null as
implementation is mandatory.

3. onUnbind()

The system invokes this when all the clients disconnect from the interface published by the service.

4. onRebind()
The system calls this method when new clients connect to the service. The system calls it after
the onBind() method.

5. onCreate()

This is the first callback method that the system calls when a new component starts the service. We need
this method for a one-time set-up.

6. onDestroy()

This method is the final clean up call for the system. The system invokes it just before the service
destroys. It cleans up resources like threads, receivers, registered listeners, etc.

<?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=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SERVICE"
android:textSize="60dp"
android:id="@+id/T1"
android:layout_centerHorizontal="true"
/>

<Button
android:id="@+id/B1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="120dp"
android:text="Start Service"
android:textSize="20dp" />

<Button
android:id="@+id/B2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="100dp"
android:text="Stop Service"
android:textSize="20dp"
android:layout_below="@+id/B1"/>

</RelativeLayout>

MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


Button B1,B2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
B1=findViewById(R.id.B1);
B2=findViewById(R.id.B2);

B1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MyService.class);
startService(intent);
}
});
B2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MyService.class);
stopService(intent);
}
});

Create MyService.java
package com.example.ifcdiv;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;

public class MyService extends Service {


private MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.start();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
player.stop();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}

Camera
These are the following two ways, in which you can use camera in your application

1. By Camera Intent
2. By Camera API

Intent

By the help of 2 constants of MediaStore class, we can capture picture and video without using the
instance of Camera class.

1. ACTION_IMAGE_CAPTURE
2. ACTION_VIDEO_CAPTURE

Using existing android camera application in our application

We can use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application


installed on your phone.
Its syntax is given below
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

Example
<?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"
android:padding="40dp"
android:orientation="horizontal"
tools:context=".MainActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CAMERA"
android:id="@+id/text"
android:textSize="20dp"
android:gravity="center"/>

<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_marginTop="81dp"
android:src="@drawable/rose"/>

<Button
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/image"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="TAKE PHOTO" />

</RelativeLayout>

Java File

package com.example.ifcdiv;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {


Button b1;
ImageView imageView;
int CAMERA_REQUEST=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1=findViewById(R.id.photo);
imageView=findViewById(R.id.image);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


startActivityForResult(i,CAMERA_REQUEST);
}
});

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode==CAMERA_REQUEST)
{
Bitmap image= (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(image);
}
}
}
BlueTooth

Bluetooth is a way to exchange data with other devices wirelessly. Android provides Bluetooth API to
perform several tasks such as:

o scan bluetooth devices


o connect and transfer data from and to other devices
o manage multiple connections

BluetoothAdapter class

By the help of BluetoothAdapter class, we can perform fundamental tasks such as initiate device
discovery, query a list of paired (bonded) devices, create a BluetoothServerSocket instance to listen for
connection requests etc.

Constants of BluetoothAdapter class

BluetoothAdapter class provides many constants. Some of them are as follows:

o String ACTION_REQUEST_ENABLE
o String ACTION_REQUEST_DISCOVERABLE
o String ACTION_DISCOVERY_STARTED
o String ACTION_DISCOVERY_FINISHED

Methods of BluetoothAdapter class

Commonly used methods of BluetoothAdapter class are as follows:

o getDefaultAdapter() returns the instance of BluetoothAdapter.


o boolean enable() enables the bluetooth adapter if it is disabled.
o boolean isEnabled() returns true if the bluetooth adapter is enabled.
o boolean disable() disables the bluetooth adapter if it is enabled.
o String getName() returns the name of the bluetooth adapter.
o void setName(String name) changes the bluetooth name.
o int getState() returns the current state of the local bluetooth adapter.
o Set<BluetoothDevice> getBondedDevices() returns a set of paired (bonded) BluetoothDevice
objects.
o boolean startDiscovery() starts the discovery process.

Example
<?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"
android:padding="40dp"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bluetooth"
android:id="@+id/text"
android:textSize="20dp"
android:gravity="center"/>
<Button
android:id="@+id/on"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_marginTop="62dp"
android:text="ON" />
<Button
android:id="@+id/discoverable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/on"
android:layout_marginTop="74dp"
android:text="DISCOVERABLE" />
<Button
android:id="@+id/off"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/discoverable"
android:layout_marginTop="104dp"
android:text="OFF" />
</RelativeLayout>

Menifest File:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ifcdiv">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

<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/Theme.IFCDiv">
<activity android:name=".ttp"></activity>
<activity android:name=".login" />
<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>

Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


Button on,off,dis;
int REQUEST_ENABLE=0;
int REQUEST_DIS=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

on=findViewById(R.id.on);
off=findViewById(R.id.off);
dis=findViewById(R.id.discoverable);

BluetoothAdapter ba=BluetoothAdapter.getDefaultAdapter();

on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!ba.isEnabled())
{
Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i,REQUEST_ENABLE);
}
}
});

dis.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!ba.isDiscovering())
{
Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(i,0);
}
}
});

off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ba.disable();
}
});
}
}
Bluetooth code to start,stop and to show paired devices

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=".MainActivity">

<Button
android:id="@+id/on"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="On" />

<Button
android:id="@+id/off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Off"
android:layout_centerInParent="true"
android:layout_below="@id/on"
/>

<Button
android:id="@+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Devices"
android:layout_centerInParent="true"
android:layout_below="@id/off"
/>

<TextView
android:id="@+id/res"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Devices:"
android:textSize="30dp"
android:layout_centerInParent="true"
android:layout_below="@id/list"
/>

</RelativeLayout>

AndroidManifest.xml:

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />


<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
MainActivity.java:

package com.example.myapplication11;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.util.Set;

public class MainActivity extends AppCompatActivity {


TextView tv;
Button on, off, list;
BluetoothAdapter mBluetoothAdapter;

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

on = findViewById(R.id.on);
off = findViewById(R.id.off);
list = findViewById(R.id.list);
tv = findViewById(R.id.res);

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
if(checkPermission()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
mBluetoothAdapter.enable();
}

Toast.makeText(MainActivity.this, "Bluetooth Turned On!",


Toast.LENGTH_SHORT).show();
}
}
});

off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mBluetoothAdapter.isEnabled()) {
if(checkPermission()) {
Intent intent = new
Intent("android.bluetooth.adapter.action.REQUEST_DISABLE");
startActivityForResult(intent, 0);
mBluetoothAdapter.disable();
}

Toast.makeText(MainActivity.this, "Bluetooth Turned Off!",


Toast.LENGTH_SHORT).show();
}
}
});

list.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!checkPermission()) return;

Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();

for (BluetoothDevice device : devices) {


tv.append("\nDevice: " + device.getName());
}

}
});

public boolean checkPermission() {


if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.BLUETOOTH_CONNECT) ==
PackageManager.PERMISSION_GRANTED) {
return true;
} else return false;
}
}

Wifi

<?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"
android:padding="40dp"
android:orientation="horizontal"
tools:context=".MainActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="WiFi"
android:id="@+id/text"
android:textSize="20dp"
android:gravity="center"/>
<Button
android:id="@+id/on"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_marginTop="62dp"
android:text="ON" />
<Button
android:id="@+id/off"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/on"
android:layout_marginTop="104dp"
android:text="OFF" />
</RelativeLayout>

Manifest File

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ifcdiv">
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

<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/Theme.IFCDiv">
<activity android:name=".ttp"></activity>
<activity android:name=".login" />
<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>

Java File

package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


Button on,off;

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

on=findViewById(R.id.on);
off=findViewById(R.id.off);

on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WifiManager wifi= (WifiManager)
getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
});

off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WifiManager wifi= (WifiManager)
getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
});

Fragment
Android Fragment is the part of activity, it is also known as sub-activity. There can be more than one
fragment in an activity.
Fragments represent multiple screen inside one activity.
We can create Fragments by extending Fragment class or by inserting a Fragment into our Activity
layout by declaring the Fragment in the activity’s layout file, as a <fragment> element.
Fragments were added in Honeycomb version of Android i.e API version 11.
We can add, replace or remove Fragment’s in an Activity while the activity is running.
Fragment can be used in multiple activities.
We can also combine multiple Fragments in a single activity to build a multi-plane UI.
We can only show a single Activity on the screen at one given point of time so we were not able to
divide the screen and control different parts separately. With the help of Fragment’s we can divide the
screens in different parts and controls different parts separately.

Example:
Develop programs for implementing fragments.
- activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">

<fragment
android:id="@+id/Frag1"
android:layout_width="match_parent"
android:layout_height="400dp"
android:name="com.example.al_libaansapp"/>
<fragment
android:id="@+id/Frag2"
android:layout_width="match_parent"
android:layout_height="400dp"
android:name="com.example.al_libaansapp"/>
</LinearLayout>

- Fragment1.xml:

<?xml version="1.0" encoding="utf-8"?>


<FrameLayout 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:background="@color/black"
tools:context=".Fragment1">

<!-- TODO: Update blank fragment layout -->


<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Fragment 1"
android:textSize="40dp"
android:textColor="@color/white"
android:textStyle="bold" />

</FrameLayout>

- Fragment2.xml:

<FrameLayout 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:background="@color/purple"
tools:context=".Fragment2">

<!-- TODO: Update blank fragment layout -->


<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Fragment 2"
android:textSize="40dp"
android:textStyle="bold"
android:textColor="@color/black"/>

</FrameLayout>
- Output:
Example (Tabbed Activity with fragment :
Fragment in Tabbed Activity
Steps:
1 Create the tabbed Activity
2 Create 3 java files and xml files as shown in diagram
3 Design the xml files (Ex fragment1_layout.xml)

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chat"/>
</LinearLayout>

4. Create java files

Fragnent1.java

package com.example.tabbedfragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment1 extends Fragment {


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1_layout,container,false);
}
}

Fragnent2.java

package com.example.tabbedfragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment2 extends Fragment {


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2_layout,container,false);
}
}

Fragnent3.java
package com.example.tabbedfragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment2 extends Fragment {


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment3_layout,container,false);
}
}

5. Now update the strings.xml file


<resources>
<string name="app_name">TabbedFragment</string>
<string name="tab_text_1">Chats</string>
<string name="tab_text_2">Calls</string>
<string name="tab_text_3">Status</string>
</resources>
6. Now open SectionPagerAdapter.java file from ui.main filder
package com.example.tabbedfragment.ui.main;

import android.content.Context;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.tabbedfragment.Fragment1;
import com.example.tabbedfragment.Fragment2;
import com.example.tabbedfragment.Fragment3;
import com.example.tabbedfragment.R;

public class SectionsPagerAdapter extends FragmentPagerAdapter {

@StringRes
private static final int[] TAB_TITLES = new int[]
{R.string.tab_text_1,R.string.tab_text_2,R.string.tab_text_3};
private final Context mContext;

public SectionsPagerAdapter(Context context, FragmentManager fm) {


super(fm);
mContext = context;
}
@Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position)
{
case 0:
fragment=new Fragment1();
break;
case 1:
fragment=new Fragment2();
break;
case 2:
fragment=new Fragment3();
break;
}
return fragment;
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}

@Override
public int getCount() {
return 3;
}
}
Animation

Animation is the process of creating motion and shape change.

1 View Animation:
 It define the properties of our Views that should be animated using a technique called Tween
Animation.
 It take the following parameters i.e. size, time duration , rotation angle, start value , end value, and
perform the required animation on that object.
 Android View animation can make animation on any View objects, such as ImageView, TextView
or Button objects.

2 Property Animation:
 Property animations are highly customizable, we can specify the duration, the number of repeats,
the type of interpolation, and the frame rate of the animation.
 The Property Animation system is always preferred for more complex animations.
 A property animation changes a property's (a field in an object) value over a specified length
of time.
 To animate something, you specify the object property that you want to animate, such as an
object's position on the screen, how long you want to animate it for, and what values you want to
animate between.

3 Drawable Animation:
 This animation allows the user to load drawable resources and display them one frame after
another.
 This method of animation is useful when user wants to animate things that are easier to represent
with Drawable resources.

Android has provided us a class called Animation


Its syntax is as follows −

Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),


R.anim.myanimation);

 Note the second parameter. It is the name of the our animation xml file.
 You have to create a new folder called anim under res directory and make an xml file under
anim folder.
This animation class has many useful functions which are listed below –
start()
This method starts the animation.
setDuration(long duration)
This method sets the duration of an animation.
getDuration()
This method gets the duration which is set by above method
end()
This method ends the animation.
cancel()
This method cancels the animation.
In order to apply this animation to an object , we will just call the startAnimation() method of the
object.
Its syntax is

ImageView image1 = (ImageView)findViewById(R.id.imageView1);


image.startAnimation(animation);

Example

<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">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="clockwise"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
android:onClick="clockwise"/>

</RelativeLayout>

res/anim/clockwise.xml.

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android">

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromDegrees="360"
android:toDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>

</set>

public class MainActivity extends Activity


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

public void clockwise(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.clockwise);
image.startAnimation(animation1);
}

Sensor

Most of the android devices have built-in sensors that measure motion, orientation, and various
environmental condition. The android platform supports three broad categories of sensors.

 Motion Sensors

These are used to measure acceleration forces and rotational forces along with three axes.

 Environmental sensors

These are used to measure the environmental changes such as temperature, humidity etc.

 Position sensors

These are used to measure the physical position of device.

Some of the sensors are hardware based and some are software based sensors. Whatever the sensor is,
android allows us to get the raw data from these sensors and use it in our application.
Android provides SensorManager and Sensor classes to use the sensors in our application.

1) SensorManager class
The SensorManager class provides methods :

o to get sensor instance,


o to access and list sensors,
o to register and unregister sensor listeners etc.

You can get the instance of SensorManager by calling the method getSystemService() and passing the
SENSOR_SERVICE constant in it.

SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);

2) Sensor class

The Sensor class provides methods to get information of the sensor such as sensor name, sensor type,
sensor resolution, sensor type etc.

3) SensorEvent class

Its instance is created by the system. It provides information about the sensor.

4) SensorEventListener interface

It provides two call back methods to get information when sensor values (x,y and z) change or sensor
accuracy changes.

Table 1. Sensor types supported by the Android platform.

Sensor Type Description Common Uses

TYPE_ACCELEROMETER Hardware Measures the Motion detection (shake,


acceleration force in tilt, etc.).
m/s2 that is applied to a
device on all three
physical axes (x, y, and
z), including the force of
gravity.

TYPE_AMBIENT_TEMPERATU Hardware Measures the ambient Monitoring air


RE room temperature in temperatures.
degrees Celsius (°C). See
note below.

TYPE_GRAVITY Software Measures the force of Motion detection (shake,


or gravity in m/s2 that is tilt, etc.).
Hardware applied to a device on all
three physical axes (x, y,
z).

TYPE_GYROSCOPE Hardware Measures a device's rate Rotation detection (spin,


of rotation in rad/s turn, etc.).
around each of the three
physical axes (x, y, and
z).
TYPE_LIGHT Hardware Measures the ambient Controlling screen
light level (illumination) brightness.
in lx.

TYPE_MAGNETIC_FIELD Hardware Measures the ambient Creating a compass.


geomagnetic field for all
three physical axes (x, y,
z) in μT.

TYPE_ORIENTATION Software Measures degrees of Determining device


rotation that a device position.
makes around all three
physical axes (x, y, z).
As of API level 3 you
can obtain the inclination
matrix and rotation
matrix for a device by
using the gravity sensor
and the geomagnetic
field sensor in
conjunction with
the getRotationMatrix()
method.

TYPE_PRESSURE Hardware Measures the ambient air Monitoring air pressure


pressure in hPa or mbar. changes.

TYPE_RELATIVE_HUMIDITY Hardware Measures the relative Monitoring dewpoint,


ambient humidity in absolute, and relative
percent (%). humidity.

TYPE_ROTATION_VECTOR Software Measures the orientation Motion detection and


or of a device by providing rotation detection.
Hardware the three elements of the
device's rotation vector.

TYPE_TEMPERATURE Hardware Measures the Monitoring temperatures.


temperature of the device
in degrees Celsius (°C).
This sensor
implementation varies
across devices and this
sensor was replaced with
the TYPE_AMBIENT_T
EMPERATURE sensor
in API Level 14
Example

<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"
android:padding="40dp"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView android:id="@+id/text"
android:textSize="20sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>

Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener {


SensorManager sm;
private Sensor acc;
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=findViewById(R.id.text1);
sm = (SensorManager) this.getSystemService(SENSOR_SERVICE);
acc=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this,acc,SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
text.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

Multimedia Framework
 The android multimedia system includes multimedia applications, multimedia framework,
OpenCore engine and hardware abstract for audio/video input/output devices.
 The goal of the android multimedia framework is to provide a consistent interface for Java services.
 The multimedia framework consists of several core dynamic libraries such as libmediajni, libmedia,
libmediaplayservice and so on
 Java classes call the Native C library Libmedia through Java JNI (Java Native Interface).
 Libmedia library communicates with Media Server guard process through Android’s Binder IPC
(inter process communication) mechanism.
 Media Server process creates the corresponding multimedia service according to the Java
multimedia applications. The whole communication between Libmedia and Media Server forms a
Client/Server model.
 In Media Server guard process, it calls OpenCore multimedia engine to realize the specific
multimedia processing functions. And the OpenCore engine refers to the PVPlayer and PVAuthor.

SQLite Database

 SQLite is an open-source relational database i.e. used to perform database operations on


android devices such as storing, manipulating or retrieving persistent data from the database.
 It is embedded in android bydefault. So, there is no need to perform any database setup or
administration task.

 SQLite is one way of storing app data. It is very lightweight database that comes with Android
OS.
 By default, Android comes with built-in SQLite Database support so we don’t need to do any
configurations.

 Android stores our database in a private disk space that’s associated with our application and
the data is secure, because by default this area is not accessible to other applications.

 The package android.database.sqlite contains all the required APIs to use an SQLite database in
our android applications.

 In android, by using SQLiteOpenHelper class we can easily create the required database and
tables for our application. To use SQLiteOpenHelper, we need to create a subclass that
overrides the onCreate() and onUpgrade() call-back methods.
 onCreate(): This method is called only once throughout the application after the database is
created
 onUpgrade():This method is called whenever there is an updation in the database like
modifying the table structure, adding constraints to the database, etc.
 We can insert data into the SQLite database by passing ContentValues to insert() method.
 In android, we can read the data from the SQLite database using the query() method in android
applications.
 We can update the data in the SQLite database using an update() method in android
applications.
Example:

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=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Registration Form"
android:layout_centerHorizontal="true"
android:textSize="40dp"
android:textStyle="bold"
android:layout_margin="20dp" />

<EditText
android:id="@+id/rollNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Enter Roll No:"
android:textSize="30dp"
android:layout_margin="20dp" />
<EditText
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Enter Name:"
android:layout_below="@id/rollNo"
android:layout_margin="20dp"
android:textSize="30dp" />

<Button
android:id="@+id/insert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_centerInParent="true"
android:text="Insert" />

<Button
android:id="@+id/update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/insert"
android:layout_centerInParent="true"
android:text="Update" />

<Button
android:id="@+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/update"
android:layout_centerInParent="true"
android:text="Delete" />

<Button
android:id="@+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/delete"
android:layout_centerInParent="true"
android:text="View" />
</RelativeLayout>

MainActivity.java
package com.example.updateddatabase;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
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 insert, update, delete, view;
EditText rollNo, name;
DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
insert = findViewById(R.id.insert);
update = findViewById(R.id.update);
delete = findViewById(R.id.delete);
view = findViewById(R.id.view);
rollNo = findViewById(R.id.rollNo);
name = findViewById(R.id.name);

db=new DatabaseHelper(this);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String rn = rollNo.getText().toString();
String nm = name.getText().toString();

boolean res = db.insertData(rn, nm);

if (res) {
Toast.makeText(getApplicationContext(), "Inserted!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error Inserting!",
Toast.LENGTH_LONG).show();
}
}
});

update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String rn = rollNo.getText().toString();
String nm = name.getText().toString();

boolean res = db.updateData(rn, nm);

if (res) {
Toast.makeText(getApplicationContext(), "Updated!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error Updating!",
Toast.LENGTH_LONG).show();
}
}
});

delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String rn = rollNo.getText().toString();

boolean res = db.deleteData(rn);

if (res) {
Toast.makeText(getApplicationContext(), "Deleted!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error Deleting!",
Toast.LENGTH_LONG).show();
}
}
});

view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
Cursor res = db.getData();

StringBuffer sb = new StringBuffer();


while(res.moveToNext()) {
sb.append("Roll No: " + res.getString(0) + "\n");
sb.append("Name: " + res.getString(1) + "\n\n");
}

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);


builder.setTitle("Students");
builder.setMessage(sb.toString());
builder.show();
}
});

}
}

DatabaseHelper.java
package com.example.updateddatabase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper


{
public DatabaseHelper(Context context)
{
super(context, "users.db", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE students(rollNo TEXT primary key, name TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS students");
}

public boolean insertData(String rn, String nm)


{
SQLiteDatabase db = getWritableDatabase();

ContentValues cv = new ContentValues();

cv.put("rollNo", rn);
cv.put("name", nm);

Long res = db.insert("students", null, cv);


if (res != -1) {
return true;
}
else return false;
}

public boolean updateData(String rn, String nm) {


SQLiteDatabase db = getWritableDatabase();

ContentValues cv = new ContentValues();

cv.put("name", nm);

int res = db.update("students", cv, "rollNo=?", new String[] { rn });

if (res != -1) {
return true;
} else return false;
}

public boolean deleteData(String rn) {


SQLiteDatabase db = getWritableDatabase();

int res = db.delete("students", "rollNo=?", new String[] { rn });

if (res != -1) {
return true;
} else return false;
}

public Cursor getData() {


SQLiteDatabase db = getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM students", null);
return c;
}
}

Program to create database:


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=".MainActivity">
<Button
android:id="@+id/create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Databasse"
android:layout_centerInParent="true"
android:textSize="40dp"
/>
</RelativeLayout>

MainActivity.java:
package com.example.database2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


SQLiteDatabase sqldb;
Button create;

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

create = findViewById(R.id.create);

create.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sqldb = openOrCreateDatabase("students2", Context.MODE_PRIVATE, null);

Toast.makeText(getApplicationContext(), "DB Created!", Toast.LENGTH_SHORT).show();


}
});
}
}

Content Provider
 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 files, in
a database or even over a network.
 Content Providers support the four basic operations, normally called CRUD-operations. (Create
,Read ,Update,Delete)
 With content providers those objects simply represent data as most often a record of a database,
but they could also be a photo on our SD-card or a video on the web.
 Whenever we want to access data from a content provider we have to specify a URI.
URIs for content providers look like this:
content://authority/optionalPath/optionalId
 Two types of URI
 directory-based URIs
 id-based URIs
1. CalendarContract SDK 14: Manages the calendars on the user’s device.
2. Browser SDK 1: Manages our web-searches, bookmarks and browsing-history.
3. CallLog SDK 1: Keeps track of our call history.
4. MediaStore SDK 1: The content provider responsible for all our media files like music,
video and pictures.
5. Settings SDK 1: Manages all global settings of our device.
6. UserDictionary SDK 3: Keeps track of words we add to the default dictionary.

1. onCreate(): This method is called when the provider is started.


2. query(): This method receives a request from a client. The result is returned as a Cursor object.
3. insert(): This method inserts a new record into the content provider.
4. delete(): This method deletes an existing record from the content provider.
5. update(): This method updates an existing record from the content provider.
6. getType(): This method returns the MIME type of the data at the given URI

Example:
Accessing contact list
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:padding="40dp"
android:orientation="vertical"
tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listview"/>

</LinearLayout>

Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ifcdiv">
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<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/Theme.IFCDiv">

<activity android:name=".ttp" />


<activity android:name=".login" />
<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>

MainActivity.java
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


ListView listView;
ArrayList<String> listdata;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView=findViewById(R.id.listview);

listdata=new ArrayList<String>();
fetchdata();
}
private void fetchdata()
{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!=
PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.READ_CONTACTS},0);

ContentResolver resolver=getContentResolver();
Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection=null;
String selection=null;
String[] selectionArg=null;
String order=null;

Cursor cursor=resolver.query(uri,projection,selection,selectionArg,order);
if(cursor.getCount()>=0)
{
while (cursor.moveToNext())
{
String
name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_
NAME));
String
number=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBE
R));
String phoneNumber=name+"\n"+number;
listdata.add(phoneNumber);
}
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,listdata);
listView.setAdapter(adapter);

Example :
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginBottom="70dp"
android:text="Content Provider"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textSize="36sp"
android:textStyle="bold" />

<EditText
android:id="@+id/textName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter name"
android:layout_marginEnd="20dp"
android:layout_marginBottom="40dp"/>

<Button
android:id="@+id/insertButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:onClick="onClickAddDetails"
android:text="Add details"
android:textStyle="bold" />

<Button
android:id="@+id/loadButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:onClick="onClickShowDetails"
android:text="Display details"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textStyle="bold" />

<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:clickable="false"
android:ems="10"
android:textColor="@android:color/holo_green_dark"
android:textSize="18sp"
android:textStyle="bold" />

</LinearLayout>

MyContentProvider.java
package com.example.sensor;
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.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

import java.util.HashMap;

public class MyContentProvider extends ContentProvider {


public MyContentProvider() {
}
// defining authority so that other application can access it
static final String PROVIDER_NAME = "com.demo.user.provider";

// defining content URI


static final String URL = "content://" + PROVIDER_NAME + "/users";
// parsing the content URI
static final Uri CONTENT_URI = Uri.parse(URL);

static final String id = "id";


static final String name = "name";
static final int uriCode = 1;
static final UriMatcher uriMatcher;
private static HashMap<String, String> values;

static {

// to match the content URI


// every time user access table under content provider
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

// to access whole table


uriMatcher.addURI(PROVIDER_NAME, "users", uriCode);

// to access a particular row


// of the table
uriMatcher.addURI(PROVIDER_NAME, "users/*", uriCode);
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.delete(TABLE_NAME, 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)) {
case uriCode:
return "vnd.android.cursor.dir/users";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}

@Override
public Uri insert(Uri uri, ContentValues values) {
long rowID = db.insert(TABLE_NAME, "", values);
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLiteException("Failed to add a record into " + uri);
}

@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_NAME);
switch (uriMatcher.match(uri)) {
case uriCode:
qb.setProjectionMap(values);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == "") {
sortOrder = id;
}
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.update(TABLE_NAME, values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
// creating object of database
// to perform query
private SQLiteDatabase db;

// declaring name of the database


static final String DATABASE_NAME = "UserDB";

// declaring table name of the database


static final String TABLE_NAME = "Users";

// declaring version of the database


static final int DATABASE_VERSION = 1;

// sql query to create the table


static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " name TEXT NOT NULL);";

// creating a database
private static class DatabaseHelper extends SQLiteOpenHelper {

// defining a constructor
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// creating a table in the database


@Override
public void onCreate(SQLiteDatabase db) {

db.execSQL(CREATE_DB_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// sql query to drop a table


// having similar name
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}

MainActivity.java
package com.example.sensor;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

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

public void onClickAddDetails(View view) {

// class to add values in the database


ContentValues values = new ContentValues();

// fetching text from user


values.put(MyContentProvider.name, ((EditText)
findViewById(R.id.textName)).getText().toString());

// inserting into database through content URI


getContentResolver().insert(MyContentProvider.CONTENT_URI, values);

// displaying a toast message


Toast.makeText(getBaseContext(), "New Record Inserted", Toast.LENGTH_LONG).show();
}

public void onClickShowDetails(View view) {


// inserting complete table details in this text field
TextView resultView= (TextView) findViewById(R.id.res);

// creating a cursor object of the


// content URI
Cursor cursor = getContentResolver().query(Uri.parse("content://com.demo.user.provider/users"),
null, null, null, null);

// iteration of the cursor


// to print whole table
if(cursor.moveToFirst()) {
StringBuilder strBuild=new StringBuilder();
while (!cursor.isAfterLast()) {
strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
resultView.setText(strBuild);
}
else {
resultView.setText("No Records Found");
}
}
}

Now create new Application


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginBottom="70dp"
android:text="Content Provider"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textSize="36sp"
android:textStyle="bold" />

<Button
android:id="@+id/loadButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:onClick="onClickShowDetails"
android:text="load data"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />

<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:clickable="false"
android:ems="10"
android:textColor="@android:color/holo_green_dark"
android:textSize="18sp"
android:textStyle="bold" />

</LinearLayout>

Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


Uri CONTENT_URI = Uri.parse("content://com.demo.user.provider/users");

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}
public void onClickShowDetails(View view) {

TextView resultView= (TextView) findViewById(R.id.res);

Cursor cursor = getContentResolver().query(Uri.parse("content://com.demo.user.provider/users"),


null, null, null, null);

if(cursor.moveToFirst()) {
StringBuilder strBuild=new StringBuilder();
while (!cursor.isAfterLast()) {
strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
resultView.setText(strBuild);
}
else {
resultView.setText("No Records Found");
}
}

AsyncTask
 Android AsyncTask is an abstract category provided by android which provides the freedom to
perform significant tasks within the background and keep the UI thread lightweight thus making
the application more responsive.
 Android AsyncTask to perform the significant tasks in background on a dedicated thread and
passing the results back to the UI thread.
 Use of AsyncTask in android application keeps the UI thread responsive at all times.
 Android AsyncTask going to do background operation on background thread and update on main
thread.
 In android we cant directly touch background thread to main thread in android development.
 asynctask help us to make communication between background thread to main thread.
Methods of AsyncTask

onPreExecute() − Before doing background operation we should show something on screen


like progressbar or any animation to user.

doInBackground(Params) − In this method we have to do background operation on


background thread. Operations in this method should not touch on any mainthread activities or
fragments.

onProgressUpdate(Progress…) − While doing background operation, if you want to update


some information on UI, we can use this method.

onPostExecute(Result) − In this method we can update UI of background operation result.

You might also like