You are on page 1of 9

Program 5.

Write a program to create an activity with two buttons START


and STOP. On pressing of the START button, the activity must start the
counter by displaying the numbers from one and the counter must keep on
counting until the STOP button is pressed. Display the counter value in a
TextViewcontrol.

XML Code:
<?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="59dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="51dp"
android:layout_marginBottom="642dp"
android:text="Counter Application"
android:textAlignment="center"
android:textColor="#2196F3"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/tv1"
android:layout_width="175dp"
android:layout_height="43dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="117dp"
android:layout_marginBottom="502dp"
android:text="Counter Value"
android:textAlignment="center" />

<Button
android:id="@+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="282dp"
android:layout_marginBottom="401dp"
android:shadowColor="#E91E63"
android:text="START"
android:textSize="18sp" />

<Button
android:id="@+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="41dp"
android:layout_marginBottom="400dp"
android:shadowColor="@color/purple_200"
android:text="STOP"
android:textColor="@color/white"
android:textSize="18sp" />

</RelativeLayout>

JAVA Code:
package com.example.lbp5;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


Button b1,b2;
TextView tc1;
int i=1;
Handler h1=new Handler();

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

b1=findViewById(R.id.bt1);
b2=findViewById(R.id.bt2);
tc1=findViewById(R.id.tv1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
h1.postDelayed(updateTimerThread,0);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
h1.removeCallbacks(updateTimerThread);
}
});

}
private final Runnable updateTimerThread=new Runnable() {
@Override
public void run() {
tc1.setText(""+i);
h1.postDelayed(this,1000);
i++;
}
};
}
// postDelayed(Runnable r, Object token, long delayMillis) Causes the Runnable r to
be added to the message queue, to be run after the specified amount of time elapses.
final void. removeCallbacks(Runnable r) Remove any pending posts of Runnable r
that are in the message queue

EXECUTION STEPS:
Step1: create a layout in XML part and drag and drop 1 text view and two buttons, name the
button as start and stop button.

Step 2: Write the code in java part to start the counter and to display the numbers from 1 on
clicking start button and on clicking stop button counter application should stop.
Step3: Execute your application to run your application on the emulator.
What is postDelayed in handler?
Public methods

postDelayed(Runnable r, Object token, long delayMillis) Causes the


final
Runnable r to be added to the message queue, to be run after the
boolean
specified amount of time elapses.

final removeCallbacks(Runnable r) Remove any pending posts of Runnable r


void that are in the message queue
How do you use postDelayed handler?

final Runnable r = new Runnable() { public void run() { handler. postDelayed(this,


1000); gameOver(); } }; When we call r. run(); the first thing it's going to do is tell
your handler to run the very same Runnable after 1000 milliseconds, and then to
call gameOver() .

How do you stop postDelayed handlers?

Added in API level 1 Remove any pending posts of callbacks and sent messages
whose obj is token. If token is null, all callbacks and messages will be removed.
Added in API level 1 Remove any pending posts of Runnable r that are in the
message queue.

How do you call every 10 seconds on Android?

Handler handler = new Handler(); private Runnable periodicUpdate = new Runnable


() { @override public void run() { // scheduled another events to be in 10
seconds later handler. postDelayed(periodicUpdate, 10*1000 //milliseconds); //
below is whatever you want to do } };

How do you repeat a method in Android?

Use a Handler in the onCreate() method. Its postDelayed() method causes the


Runnable to be added to the message queue and to be run after the specified
amount of time elapses (that is 0 in given example). Then this will queue itself after
fixed rate of time (1000 milliseconds in this example).

A Handler allows you to send and process Message and Runnable objects associated


with a thread's MessageQueue. Each Handler instance is associated with a single
thread and that thread's message queue.

main uses for a Handler: (1) to schedule messages and runnables to be executed at
some point in the future;
PostDelayed(IRunnable, Int64)
Causes the Runnable r to be added to the message queue, to be run after
the specified amount of time elapses.

A thread, in the context of Java, is the path followed when executing a


program. ... In Java, creating a thread is accomplished by implementing an
interface and extending a class.

What is the problem with java thread?


Java threads are one-time use only and die after executing its run method.
Can we improve upon it?
The Thread is a double edged sword. We can speed up the execution by
distributing the tasks among threads of execution, but can also slow it down
when threads are in excess. Thread creation in itself is an overhead. So, the
best option is to have an optimum number of threads and reuse them for tasks
execution.
Model for thread reusability:
1. The thread is kept alive, in a loop via it’s run() method.
2. The task is executed serially by that thread and is maintained in a queue
(MessageQueue).
3. The thread must be terminated when done.
What is the Android’s way of doing it?
The above model is implemented in the Android via Looper,
 Handler, and HandlerThread. The System can be visualized to be a vehicle as
in the article’s cover.
1. MessageQueue is a queue that has tasks called messages which should
be processed.
2. Handler enqueues task in the MessageQueue using Looper and also
executes them when the task comes out of the MessageQueue.
3. Looper is a worker that keeps a thread alive, loops
through MessageQueue and sends messages to the
corresponding handler to process.
4. Finally Thread gets terminated by calling Looper’s quit() method.
One thread can have only one unique Looper and can have many unique
Handlers associated with it.rent thread than your own.

Recent
package com.example.counter;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.os.Handler;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

TextView tv;

Button b1,b2;

int i=1;

Handler myhandler = new Handler();

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

b1=findViewById(R.id.bt1);

b2=findViewById(R.id.bt2);
tv = findViewById(R.id.counter);

b1.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v)

myhandler.postDelayed(UpdateTimerThread, 1000);

});

b2.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v)

myhandler.removeCallbacks(UpdateTimerThread);

});

public Runnable UpdateTimerThread = new Runnable() {

@Override

public void run()

tv.setText(""+i);

myhandler.postDelayed(UpdateTimerThread, 1000);

i++;

};

You might also like