VALUE ADDED
(Services)
Aim:- To perform programme of Service
Pre-Requisite:- Android Studio
Code:-
/*Ac#vity_main.xml*\
<?xml version="1.0"
encoding="utf-8"?>
<androidx.constraintlayout.widge
t.ConstraintLayout
xmlns:android="http://
schemas.android.com/apk/res/
android"
xmlns:app="http://
schemas.android.com/apk/res-
auto"
xmlns:tools="http://
schemas.android.com/tools"
android:layout_width="match_pare
nt"
android:layout_height="match_par
ent"
tools:context=".MainActivity">
<TextView
android:id="@+id/
textView"
android:layout_width="wrap_conte
nt"
android:layout_height="wrap_cont
ent"
android:layout_marginStart="114d
p"
android:layout_marginLeft="114dp
"
android:layout_marginTop="88dp"
android:text="Services
Demo"
android:textSize="24sp"
app:layout_constraintStart_toSta
rtOf="parent"
app:layout_constraintTop_toTopOf
="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_conte
nt"
android:layout_height="wrap_cont
ent"
android:layout_marginTop="250dp"
android:onClick="StartServices"
android:text="Start
Services"
app:layout_constraintEnd_toEndOf
="parent"
app:layout_constraintStart_toSta
rtOf="parent"
app:layout_constraintTop_toTopOf
="parent" />
<Button
android:id="@+id/
button2"
android:layout_width="wrap_conte
nt"
android:layout_height="wrap_cont
ent"
android:layout_marginBottom="259
dp"
android:onClick="StopServices"
android:text="Stop
Services"
app:layout_constraintBottom_toBo
ttomOf="parent"
app:layout_constraintEnd_toEndOf
="parent"
app:layout_constraintStart_toSta
rtOf="parent" />
</
androidx.constraintlayout.widget
.ConstraintLayout>
/*MainAc#vity.java*\
package com.example.services;
import
androidx.appcompat.app.AppCompat
Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity
extends AppCompatActivity {
@Override
protected void
onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceStat
e);
setContentView(R.layout.activity
_main);
}
public void
StartServices(View v)
{
startService(new
Intent(getBaseContext(),
MyService.class));
}
public void
StopServices(View v)
{
stopService(new
Intent(getBaseContext(),
MyService.class));
}
}
/*MyService.java*\
package com.example.services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import
androidx.annotation.Nullable;
public class MyService extends
Service {
@Nullable
@Override
public IBinder onBind(Intent
intent) {
return null;
}
@Override
public int
onStartCommand(Intent intent,
int flags, int startId) {
// Let it continue
running until it is stopped.
Toast.makeText(this,
"Service Started",
Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this,
"Service Destroyed",
Toast.LENGTH_LONG).show();
}
}
Output :-