Skip to content

Simple Async with Timer

Yuri Shmakov edited this page Nov 3, 2016 · 4 revisions

MainActivit.java:

public class MainActivity extends MvpAppCompatActivity implements HelloWorldView {
	@InjectPresenter
	HelloWorldPresenter mHelloWorldPresenter;
	private TextView mTimerTextView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mTimerTextView = (TextView) findViewById(R.id.timer_text_view);
	}

	@Override
	public void showTimer() {
		mTimerTextView.setVisibility(View.VISIBLE);
	}

	@Override
	public void hideTimer() {
		mTimerTextView.setVisibility(View.GONE);
	}

	@Override
	public void setTimer(int seconds) {
		mTimerTextView.setText(getString(R.string.timer, seconds));
	}

	@Override
	public void showMessage(int message) {
		TextView messageTextView = new TextView(this);
		messageTextView.setText(message);
		messageTextView.setTextSize(40);
		messageTextView.setGravity(Gravity.CENTER_HORIZONTAL);
		((ViewGroup) findViewById(R.id.activity_main)).addView(messageTextView);
	}
}

HelloWorldPresenter.java: ```java @InjectViewState public class HelloWorldPresenter extends MvpPresenter { public HelloWorldPresenter() { AsyncTask asyncTask = new AsyncTask() { @Override protected void onPreExecute() { getViewState().showTimer(); }
		@Override
		protected Void doInBackground(Void... voids) {
			for (int i = 5; i > 0; i--) {
				publishProgress(i);
				sleepSecond();
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			getViewState().setTimer(values[0]);
		}

		@Override
		protected void onPostExecute(Void aVoid) {
			getViewState().hideTimer();
			getViewState().showMessage(R.string.hello_world);
		}

		private void sleepSecond() {
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException ignore) {}
		}
	};

	asyncTask.execute();
}

}

<br />
HelloWorldView.java:
```java
public interface HelloWorldView extends MvpView {
	void showTimer();

	void hideTimer();

	void setTimer(int seconds);

	void showMessage(int message);
}
Screen video capture ![](https://habrastorage.org/files/966/b76/0bc/966b760bc35840eb89f86d707aaeaeff.gif)