[embedyt] https://www.youtube.com/watch?v=QfQE1ayCzf8[/embedyt]
activity_main.xmlMainActivity.java
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:gravity="center" android:orientation="vertical" tools:context="com.codinginflow.threadexample.MainActivity"> <Switch android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" /> <Button android:id="@+id/button_start_thread" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="startThread" android:text="Start" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="stopThread" android:text="Stop" /> </LinearLayout>
package com.codinginflow.threadexample; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private Button buttonStartThread; private Handler mainHandler = new Handler(); private volatile boolean stopThread = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonStartThread = findViewById(R.id.button_start_thread); } public void startThread(View view) { stopThread = false; ExampleRunnable runnable = new ExampleRunnable(10); new Thread(runnable).start(); /* ExampleThread thread = new ExampleThread(10); thread.start(); */ /* new Thread(new Runnable() { @Override public void run() { //work } }).start(); */ } public void stopThread(View view) { stopThread = true; } class ExampleThread extends Thread { int seconds; ExampleThread(int seconds) { this.seconds = seconds; } @Override public void run() { for (int i = 0; i < seconds; i++) { Log.d(TAG, "startThread: " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } class ExampleRunnable implements Runnable { int seconds; ExampleRunnable(int seconds) { this.seconds = seconds; } @Override public void run() { for (int i = 0; i < seconds; i++) { if (stopThread) return; if (i == 5) { /* Handler threadHandler = new Handler(Looper.getMainLooper()); threadHandler.post(new Runnable() { @Override public void run() { buttonStartThread.setText("50%"); } }); */ /* buttonStartThread.post(new Runnable() { @Override public void run() { buttonStartThread.setText("50%"); } }); */ runOnUiThread(new Runnable() { @Override public void run() { buttonStartThread.setText("50%"); } }); } Log.d(TAG, "startThread: " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }