Mad Unit-4
Mad Unit-4
INDEX:
Introduction to services
What is Service?
Service is a component which keeps an app running in the background to perform long-
running operations based on our requirements.
For Service, we don't have any user interface and it will run the apps in the background
like playing the music in the background or handle network operations when the user in a different
app, interacting content providers.
1. Foreground Services:
Example
2. Background Services:
These services run in the background, such that the user can’t
see or access them.
These are the tasks that don’t need the user to know them.
Background services have own lifecycle that independent fromactivity or fragment that they
were created.
Example
Bound services perform their task as long as any applicationcomponent is bound to it.
Many components can bind to one service at a time, but once theyall unbind, the service will
destroy.
2. Bound Service
1. Started Service
Once it started, it will run indefinitely in background even if the component that started is
destroyed.
2. Bound Service
A bound service offers a client-server interface that allows components to interact with the
service, send requests, get results, and even do so across processes with interprocess communication
(IPC).
This service runs in the background as long as another application isbound to it.
The service base class defines certain callback methods to performoperations on applications.
onStartCommand()
onBind()
onCreate()
onUnbind()
onDestroy()
onRebind()
MOBILE APPLICATION DEVELOPMENT
1
onStartCommand()
The system calls this method when another component, such as an activity, requests
that the service be started, by calling startService().
If you implement this method, it is your responsibility to stop the service when its work is
done, by calling stopSelf() or stopService() methods.
2
onBind()
The system calls this method when another component wants to bind with the service by
calling bindService().
If you implement this method, you must provide an interface that clients use to communicate
with the service, by returning an IBinder object.
You must always implement this method, but if you don't want to allow binding, then you
should return null.
3
onUnbind()
The system calls this method when all clients have disconnected from a particular interface
published by the service.
4
onRebind()
The system calls this method when new clients have connected to the service, after it had
previously been notified that all had disconnected in its onUnbind(Intent).
5
onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind().
MOBILE APPLICATION DEVELOPMENT
6
onDestroy()
The system calls this method when the service is no longer used and isbeing destroyed.
Your service should implement this to clean up any resources such as threads, registered
listeners, receivers, etc.
activity_main.xml:
MainActivity.java
import android.content.Intent; import android.os.Bundle; import android.view.View; import
android.widget.Button;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implementsView.OnClickListener {
Button buttonStart, buttonStop;@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); buttonStart = findViewById(R.id.buttonStart); buttonStop
= findViewById(R.id.buttonStop); buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
public void onClick(View src) {switch (src.getId()) {
case R.id.buttonStart:
startService(new Intent(this, MyService.class)); break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class)); break;
}
}}
AndroidManifest.xml:
<service
android:name=".MyService" android:enabled="true" android:exported="true"></service>
Output:
MOBILE APPLICATION DEVELOPMENT
Intent services
The Service will be started whenever a client sends a request, and it will be stopped after
each Purpose has been addressed.
Here, a worker thread is created and all requests are handled using the worker thread but at a
time, only one request will be processed.
To use IntentService you have to extend the IntentService and implement the
onHandleIntent(android.content.Intent).
1. Thread management: It automatically processes all incoming requests in a separate thread taking
the burden of thread management away fromthe developer.
2. Request Queue: It queues up all the incoming requests and they areprocessed one by one
MOBILE APPLICATION DEVELOPMENT
3. Stop point: Once the request Queue is empty it automatically stops itself, so the developer need
not worry about handling the service lifecycle.
Service IntentService
You can use Service for the tasks that don’t If you want some background task to be performed
require any UI and also it is not a very long for a very long period oftime, then you should use
running task. the IntentService.
To start a Service you need to call the To start the IntentService by calling
onStartService() Context.startService(Intent)
method
Service always runs on the Mainthread The IntentService runs on a separate Worker
thread
There is a chance of blocking the main thread Tasks will be performed on a queue basis i.e,First
come first serve basis.
Multi–Threading
This means when a process is broken, the equivalent number ofthreads are available.
MOBILE APPLICATION DEVELOPMENT
Threading in Android
In Android, you can categorize all threading components into two basiccategories:
1. Threads that are attached to an activity/fragment: These threads are tied to the lifecycle of the
activity/fragment and are terminated assoon as the activity/fragment is destroyed.
2. Threads that are not attached to any activity/fragment: These threads can continue to run beyond
the lifetime of the activity/fragment (if any) from which they were spawned.
MOBILE APPLICATION DEVELOPMENT
Handler in android
Uses of Handler
In android Handler is mainly used to update the main thread from background thread or other than
main thread. There are two methods are inhandler.
Looper
will take care of dispatching work on its message-loop
2. Secondly it will implement the callback for processing thosemessages when they are dispatched
by the Looper
Write Ex no 6
AsyncTask
Android AsyncTask is an abstract class provided by Android which gives us the liberty to
perform heavy tasks in the background and keep the UI thread light thus making the application more
responsive.
Due to this single thread model tasks that take longer time to fetchthe response can make the
application non-responsive.
To avoid this we use android AsyncTask to perform the heavy tasks in background on a
dedicated thread and passing the results back to the UI thread.
MOBILE APPLICATION DEVELOPMENT
Hence use of AsyncTask in android application keeps the UI thread responsive at all times.
doInBackground() : This method contains the code which needs to be executed in background. In
this method we can send results
multiple times to the UI thread by publishProgress() method. To notify that the background
processing has been completed we justneed to use the return statements
onPreExecute() : This method contains the code which is executed before the background processing
starts
onPostExecute() : This method is called after doInBackground method completes processing. Result
from doInBackground is passedto this method
onProgressUpdate() : This method receives progress updates from doInBackground method, which
is published via publishProgress method, and this method can use this progress update to update the
UI thread
The following code must be present in the MainActivity class in order to launch an
AsyncTask.
MyTask myTask = new MyTask();myTask.execute();
The execute method is used to start the background thread in theexcerpt above, where we’ve
used a sample class name that extends AsyncTask.
@Override
// ...
}
@Override
@Override
protected void onPostExecute(String string) {super.onPostExecute(string);
// ...
}
}
}
MOBILE APPLICATION DEVELOPMENT
Broad cast
Broadcasts are messages that the Android system and Android appssend when events occur
that might affect the functionality of other apps.
For example, the Android system sends an event when the systemboots up, when power is
connected or disconnected, and when headphones are connected or disconnected.
Broadcasts are messaging components used for communicating across apps when events of
interest occur.
There are two types of broadcasts:
System broadcasts
A system broadcast is a message that the Android system sendswhen a system event occurs.
System broadcasts are wrapped in Intent objects.
The intent object's action field contains event details such
as android.intent.action.HEADSET_PLUG, which is sent when a wired headset is connected or
disconnected.
The intent can also contain more data about the event in its extra field, for example a
boolean extra indicating whether a headset is connected or disconnected.Examples:
When the device boots, the system broadcasts a system Intent with the action
ACTION_BOOT_COMPLETED.
When the device is disconnected from external power, the system sends a system Intent with the
action
field ACTION_POWER_DISCONNECTED.
Broadcast receivers
When any of these events occur it brings the application into action by either creating a status
bar notification or performing a task.
MOBILE APPLICATION DEVELOPMENT
For eg : a Broadcast receiver triggers battery Low notification that you see on your mobile
screen..
Broadcast receivers helps our app communicate with Android OS andother apps.
Two important steps to make Broadcast Receiver works for thesystem broadcasted items:
Syntax
Override
Public void onReceive(context: Context, intent: Intent)
}
}
1. Statically (manifest-declared) - This receiver can be registered via the AndroidManifest.xml file.
2. Dynamically (context-registered) - This registers a receiver dynamically via the
Context.registerReceiver() method.
<receiver android:name=".MyBroadcastReceiver"
android:exported="true">
<intent-filter>
<action
android:name="android.net.conn.CONNECTIVITY_CHANGE""/>
</intent-filter>
</receiver>
MOBILE APPLICATION DEVELOPMENT
Secondly, create class as a subclass of BroadcastReceiver class and overriding the onReceive()
method where each message is received as aIntent object parameter.
intentFilter.addAction(getPackageName() +
"android.net.conn.CONNECTIVITY_CHANGE");
Android TelephonyManager
activity_main.xml
<RelativeLayout xmlns:androclass="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=".MainActivity" >
</RelativeLayout>
MainActivity.java
textView1=(TextView)findViewById(R.id.textView1);
String strphoneType="";
int phoneType=tm.getPhoneType();
switch (phoneType)
{
case (TelephonyManager.PHONE_TYPE_CDMA):strphoneType="CDMA";
break;
case (TelephonyManager.PHONE_TYPE_GSM):strphoneType="GSM";
break;
case (TelephonyManager.PHONE_TYPE_NONE):strphoneType="NONE";
break;
}
boolean isRoaming=tm.isNetworkRoaming();
AndroidManifest.xml
Output:
MOBILE APPLICATION DEVELOPMENT
Android offers the Messenger app that can send and receive SMSmessages.
//Get the SmsManager instance and call the sendTextMessage method to send message
SmsManager sms=SmsManager.getDefault(); sms.sendTextMessage("8802177690", null, "hello
javatpoint", pi,null);
activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity" >
<Button
android:id="@+id/button1" android:layout_width="wrap_content"
MOBILE APPLICATION DEVELOPMENT
android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2" android:layout_marginLeft="34dp"
android:layout_marginTop="48dp" android:text="Send SMS" />
</RelativeLayout>
<uses-permission android:name="android.permission.SEND_SMS"/>
MainActivity.java
package com.example.sendsms;
import android.os.Bundle;
import android.app.Activity; import android.app.PendingIntent;import android.content.Intent;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; import android.widget.EditText;import android.widget.Toast;
mobileno=(EditText)findViewById(R.id.editText1);
message=(EditText)findViewById(R.id.editText2); sendsms=(Button)findViewById(R.id.button1);
@Override
public void onClick(View arg0) {
String no=mobileno.getText().toString(); String msg=message.getText().toString();
//Get the SmsManager instance and call the sendTextMessage methodto send message
SmsManager sms=SmsManager.getDefault();sms.sendTextMessage(no, null, msg, pi,null);
MOBILE APPLICATION DEVELOPMENT
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
OUTPUT:
MOBILE APPLICATION DEVELOPMENT
Making calls
In android, we can easily make a phone call from our android applications by invoking built-in phone
calls app
using Intents action (ACTION_CALL).
To make a phone call using Intent object in android application, we need to write the code like as
shown below.
<Button
android:id="@+id/button1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"android:layout_marginTop="118dp" android:text="Call" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentTop="true" android:layout_centerHorizontal="true"
android:layout_marginTop="25dp" android:ems="10" />
</RelativeLayout>
MainActivity.java
package com.example.phonecall;
@Override
public void onClick(View arg0) {
String number=edittext1.getText().toString();
Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:"+number));
startActivity(callIntent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
OUTPUT:
MOBILE APPLICATION DEVELOPMENT