Android/非同期処理/HandlerRunnable
提供: 初心者エンジニアの簡易メモ
AsyncTaskはAndroid11から非推奨となったので非同期処理はこちら推奨。
サンプル
final TextView textView = findViewById(R.id.text1); final Handler handler = new Handler(Looper.getMainLooper()); new Thread(new Runnable() { @Override public void run() { final String msg = "background exec"; if (handler != null) { handler.post(new Runnable() { @Override public void run() { if (textView != null) { textView.setText(msg); } } }); } } }).start();
参考:https://qiita.com/8yabusa/items/f8c9bb7eb81175c49e97
サンプル(Runnableクラス切り分け)
MainActivity.java
final TextView textView = findViewById(R.id.text1); final Handler handler = new Handler(Looper.getMainLooper()); MyRunnableTask task = new MyRunnableTask(handler, textView); new Thread(task).start();
MyRunnableTask.java
import android.os.Handler; import android.widget.TextView; public class MyRunnableTask implements Runnable { Handler mHandler; TextView mTextView; public MyRunnableTask(Handler handler, TextView textView) { mHandler = handler; mTextView = textView; } public void run() { final String msg = "background exec"; if (mHandler != null) { mHandler.post(new Runnable() { @Override public void run() { if (mTextView != null) { mTextView.setText(msg); } } }); } } }
サンプル(ネットワーク処理&View処理)
ネットワーク処理はマルチスレッドで処理して、ViewはUiスレッドで処理する。
MainActivity.java
final TextView textView = findViewById(R.id.text1); final Handler uiHandler = new Handler(Looper.getMainLooper()); HandlerThread thread = new HandlerThread("other"); thread.start(); final Handler handler = new Handler(thread.getLooper()); MyRunnableTask task = new MyRunnableTask(uiHandler, handler, textView); new Thread(task).start();
MyRunnableTask.java
import android.os.Handler; import android.widget.TextView; public class MyRunnableTask implements Runnable { Handler mUiHandler; Handler mHandler; TextView mTextView; public MyRunnableTask(Handler uiHandler, Handler handler, TextView textView) { mUiHandler = uiHandler; mHandler = handler; mTextView = textView; } public void run() { final String ret = ""; if (mHandler != null) { mHandler.post(new Runnable() { @Override public void run() { final CustomHttpURLConnection http = new CustomHttpURLConnection(); try { String encode = URLEncoder.encode(param1, "UTF-8"); String url = "https://h2ch.com/upword?param1=" + encode; http.execGet(url); Log.i("http", http.getBody()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (mUiHandler != null) { mUiHandler.post(new Runnable() { @Override public void run() { if (mTextView != null) { mTextView.setText(ret); } } }); } } }); } } }