- 
                Notifications
    
You must be signed in to change notification settings  - Fork 34
 
Simple Async with Timer
        Yuri Shmakov edited this page Aug 15, 2017 
        ·
        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:
@InjectViewState
public class HelloWorldPresenter extends MvpPresenter<HelloWorldView> {
	public HelloWorldPresenter() {
		AsyncTask<Void, Integer, Void> asyncTask = new AsyncTask<Void, Integer, Void>() {
			@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();
	}
}HelloWorldView.java:
public interface HelloWorldView extends MvpView {
	void showTimer();
	void hideTimer();
	void setTimer(int seconds);
	void showMessage(int message);
}