Pandiyan Mani
4 min readAug 11, 2021

--

Android Application Component

Android Application Component are the building blocks of an android app.There are classfied in to four

Activity

Service

Broadcastreceiver

Content provider

Before Activity we can have a look in to Service

What is Service?

If you want to perform any long running operation at the background without user interaction we can use service it will run if we switch from one application to other.

Service doesnt contain any user interface that is UI.

Service runs on main thread we have to perform with thread in order to make it background thread.

what are lifecyle Of service?

start service with unbound service : oncreate() →onstartcommand() →Service running →if its killed by system →onDestroy().

start service with bound service : oncreate() →onstartcommand() →onBind() →onUnbind →onRebind →Service running →if its killed by system →onDestroy().

what are methods Of service and their usage?

oncreate() : it will be called on the start of service for the first time mainly we use this method for initilzing any values for the first time.

onstartcommand() : whenever the service get started it will be called it has return type

START_STICKY -- which restart service when its killed by the system.
START_NOT_STICKY -- If you dont want to restart service killed by the system.
START_REDELIVER_INTENT -- which retain the intent used for starting service and by using that intent it start the service.

onBind() : its a client service communication if you want to communicate from service to client we use this method.If we implement this method we have to create an interface that communicate between service and client.

onUnbind() : if all the connection to the particular interface is disconnected this method will be called.

onRebind() : if a new connection has been established after unbind this method will be invoked.

onDestroy() : this method is called when service has been stopped we use this method to free up resources.

How to start unbound service and bound service?

Starting unbound service

Intent ins =new Intent(Mainclass.this,Sampleservice.class);
startService(ins);

Starting bound service

bindService(ins,connection, Context.BIND_AUTO_CREATE);

Program that pass data every second from service to Activity

Service class

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import androidx.annotation.Nullable;
import java.util.Timer;
import java.util.TimerTask;

public class Sampleservice extends Service
{

Timer timer=null;
LocalBinder ibind =new LocalBinder();
Callback objcallback = null;
int count = 0;

@Nullable
@Override
public IBinder onBind(Intent intent) {
System.out.println("--->onBind");
return ibind;
}

@Override
public void onCreate() {
super.onCreate();
System.out.println("--->Oncreate");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("--->onStartCommand");
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
System.out.println("--->onDestroy");
if(timer != null)
{
timer.cancel();
timer = null;
}
}

public void startcounter()
{
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("--->Hi");
objcallback.getintvalue(count++);
}
},0,1000);
}

public void registerinterfacefromactivity(Activity ac)
{
this.objcallback = (Callback)ac;
}

class LocalBinder extends Binder
{
public Sampleservice getInstance()
{
return Sampleservice.this;
}
}

public interface Callback
{
public void getintvalue(int a);
}
}

Activity Class

public class Mainclass extends AppCompatActivity implements Sampleservice.Callback {

Sampleservice myservice = null;
Button button_start,button_stop;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_start = findViewById(R.id.button_start);
button_stop = findViewById(R.id.button_stop);
button_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent ins =new Intent(Mainclass.this,Sampleservice.class);
startService(ins);
bindService(ins,connection, Context.BIND_AUTO_CREATE);
}
});
button_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent ins =new Intent(Mainclass.this,Sampleservice.class);
stopService(ins);
unbindService(connection);
}
});
}

ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Sampleservice.LocalBinder binder = (Sampleservice.LocalBinder)service;
myservice = binder.getInstance();
myservice.registerinterfacefromactivity(Mainclass.this);
myservice.startcounter();
}

@Override
public void onServiceDisconnected(ComponentName name) {

}
};

@Override
public void getintvalue(int a) {
System.out.println("--->"+a);
}
}

What is Activity?

Activity is an user interface where user can communicate.for eg in email app — list of email displaying is an activity and composing email is another activity.

What is Activity lifecyle?

oncreate() →onstart() →onResume() →onRestart()→onpause() →onstop() →ondestroy()

How lifecyle called from one activity to another?

Activity A on launch → onCreate,onStart,onResume method will be called if we minimize onPause,onStop method will be called →if it move from Activity A to Activity B then in Activity A — ->onPause will be called first followed by Activity B→ onCreate,onStart,onResume method then onStop method of Activity A at last.

If we come back from Activity B → onPause will be called followed by Activity A — ->onRestart,onStart,onResume then onStop,onDestroy method of Activity B at last.

what is BroadcastReceiver?

It simply respond to brodcast message either from other application or from the system itself.we can also create or generate our own intent using sendbroadcast() method.

By default BroadcastReceiver works on main thread but we can make it run on worker thread by using Handler thread but dont forget to exit the thread during unregister.

 HandlerThread handlerThread = new HandlerThread("ht");
handlerThread.start();
Looper looper = handlerThread.getLooper();
Handler handler = new Handler(looper);
IntentFilter filter = new IntentFilter("MyAction");
Myreceiver is = new Myreceiver();
registerReceiver(is,filter,"1",handler);

If you want to perform any task on background one at a time the we can go for Handler thread because it contain is own looper.It perform the task on worker thread.

How to Create BroadcastReceiver?

We can create by extending class BroadcastReciver and override the onreceive(context,intent) method.The messages are received in the form of intent

public class Myreceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Message Received",Toast.LENGTH_LONG).show();
}
}

How to Register BroadcastReceiver?

you can register the event in the AndroidManifest.xml file of your application or you can register the broadcast via the Context.registerReceiver() method

<receiver android:name=".Myreceiver">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"></action>
</intent-filter>
</receiver>

The IntentFilter specifies which event your receiver should listen to

Inside Activitty class for registering

IntentFilter filter = new IntentFilter("android.intent.action.AIRPLANE_MODE");
Myreceiver is = new Myreceiver();
registerReceiver(is,filter);

Unregistering Receiver

unregisterReceiver(is);

Creating Custom intents

We can also generate or create our own intents using sendbroadcast() method

Intent in =new Intent(Mainclass.this,Myreceiver.class);
sendBroadcast(in.setAction("Hi"));
public class Myreceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Message Received "+intent.getAction(),Toast.LENGTH_LONG).show();
}
}

what is LocalBroadcastReceiver?

If you communication is not between application then its safe to use localbroadcast manager instead of global brodcast.Because the data may be accessed by other application and there will be security hole.

For that first we have to create instance for the LocalBroadcastManager

LocalBroadcastManager la= LocalBroadcastManager.getInstance(Mainclass.this);

And assign it to the sendbroadcast() method

Intent in =new Intent(Mainclass.this,Myreceiver.class);
la.sendBroadcast(in.setAction("Hi"));

--

--