Showing posts with label Thread. Show all posts
Showing posts with label Thread. Show all posts

Tuesday, November 15, 2016

Handling Thread in Android

Dear All

As we know how thread plays an important role to perform multiple task simultaneously in Java.
In this example i am handling the Main Thread and performing an operation to wait for a while.
Just read the example.
A. Output will be
1. Before Button Pressed



2. After 5 sec of Button Pressed



B. xml file is as   activity_main.xml

<TextView    android:id="@+id/myTextView"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_centerHorizontal="true"

    android:layout_centerVertical="true"

    android:text="Hello_world" />
<Button        android:id="@+id/button1"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_below="@+id/myTextView"

    android:layout_centerHorizontal="true"

    android:layout_marginTop="48dp"

    android:onClick="buttonPressed"

    android:text="Click Me" />

C. Java Code  MainActivity.java

package com.example.ravigodara.singlethread;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView =(TextView)findViewById(R.id.myTextView);
    }
    public void buttonPressed(View view)
    {
        long endTime = System.currentTimeMillis() + 5*1000;
        while (System.currentTimeMillis() < endTime) {
            synchronized (this) {
                try {
                    wait(endTime - System.currentTimeMillis());
                }
                catch (Exception e) {
                }
            }
        }

        textView.setText("Button Pressed");

    }

}