私はまず、this Android Performance Patterns videoをチェックして、あなたの処分でいくつかのオプションを確認することをお勧めします。また、ライフサイクル環境(たとえばActivities
、Fragments
)でマルチスレッドを実行しないようお勧めします。
onClick
の例では、R.string.done
は、最初のスレッドが処理を完了する前に表示される可能性があります。私はそれが本当にあなたが望むものではないと仮定しています。
あなたが取り組んでいる問題、使用しているツール、またはあなたがフォローしているアーキテクチャについては何も知らないので、ここにはがあります。少し一般的なやり方です。 onClick
実装の各Thread
には、ソートのステータスがあります。あなたは、単純な抽象化とコードでこれを表すことができます:
class Holder {
@StringRes int status;
Runnable runnable;
Holder(@StringRes int status, @NonNull Runnable runnable) {
this.status = status;
this.runnable = runnable;
}
}
お知らせRunnable
ではなくThread
の使用されています。
あなたも順番に実行しています。あなたが例えば流体、表情豊かなAPIを提供し、シンプルList
またはQueue
とコードでこれを表すことができます:
service
が
ExecutorServiceある
@Override
public void onClick(View v) {
final Runnable runnable = new StatusRunnableBuilder(view)
.addStep(R.string.launching_text, launchingRunnable)
.addStep(R.string.almost_done, almostDoneRunnable)
.withFinalStatus(R.string.finally_done)
.build();
service.execute(runnable);
}
:
class StatusRunnableBuilder {
private final WeakReference<TextView> viewRef;
private final Queue<Holder> queue;
@StringRes private int finalStatus;
StatusRunnableBuilder(@NonNull TextView view) {
viewRef = new WeakReference<>(view);
queue = new ArrayDeque<>();
}
StatusRunnableBuilder addStep(@StringRes int status,
@NonNull Runnable runnable) {
queue.add(new Holder(status, runnable));
return this;
}
StatusRunnableBuilder withFinalStatus(@StringRes int status) {
finalStatus = status;
return this;
}
Runnable build() {
return new Runnable() {
@Override
public void run() {
for (Holder item: queue) {
updateStatus(item.status);
item.runnable.run();
}
if (finalStatus != 0) {
updateStatus(finalStatus);
}
}
};
}
private void updateStatus(@StringRes final int status) {
final TextView view = viewRef.get();
if (view != null) {
view.post(new Runnable() {
@Override
public void run() {
// As this has been posted to a queue,
// it could have been processed with some delay,
// so there is no guarantee the view is still present.
// Let's check again.
final TextView v = viewRef.get();
if (v != null) {
v.setText(status);
}
}
});
}
}
}
次に、あなたのonClick
は次のようになり任意のライフサイクルイベントを作成/停止することができます。:
@Override
protected void onStart() {
super.onStart();
service = Executors.newSingleThreadExecutor();
}
@Override
protected void onStop() {
super.onStop();
service.shutdownNow();
}
別のスレッドを使用してtextviews – Zoe
を設定し、そのスレッド内の 'runOnUiThread'を使用するが、だからあなたは、いくつかの秒後、ユーザーに異なるメッセージを表示するようにしたいですか? –
Rxjavaのzip演算子を使用し、これらの観測値を組み合わせることで、同時に応答をuiスレッドに表示し、その間に進行状況を表示できます。 [here](http://reactivex.io/documentation/operators/zip.html) – Debdeep