package com.jim.testapp; import android.app.Activity; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.Button; class MyHandler extends Handler { private Activity mActivity; private Button btn; public MyHandler(Activity activity) { mActivity = activity; btn = (Button)activity.findViewById(R.id.button); } @Override public void handleMessage(Message msg) { Integer integer = (Integer) msg.obj; switch (msg.what) { case MainActivity.MSG_ONE: btn.setText(integer.toString()); break; } } } class MyAsyncTask extends AsyncTask<String, Integer, Integer> { private MainActivity mActivity; private Button btn; public MyAsyncTask(MainActivity activity) { mActivity = activity; btn = (Button)activity.findViewById(R.id.button); } @Override protected void onPreExecute() { super.onPreExecute(); btn.setText("Loading start"); } @Override protected void onPostExecute(Integer integer) { super.onPostExecute(integer); btn.setText("Loading finished"); Log.i(MainActivity.TAG, "Result is " + integer); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); btn.setText("Loading " + values[0] + "%"); } @Override protected Integer doInBackground(String... params) { Log.i(MainActivity.TAG, params[0]); for (int i = 1; i <= 10; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } publishProgress(i*10); } return 0; } } public class MainActivity extends AppCompatActivity { public static final String TAG = "jimtest"; public static final int MSG_ONE = 1; public static final int MSG_TWO = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //MyAsyncTask task = new MyAsyncTask(this); //task.execute("i am the param"); final MyHandler h = new MyHandler(this); Runnable r = new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { h.obtainMessage(MSG_ONE, new Integer(i)).sendToTarget(); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } }; new Thread(r).start(); } }