Java tutorial
/* * Copyright (C) 2011 Nguyen Hoang Ton, a.k.a Ton Nguyen - tonng86@gmail.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.tonnguyen.livelotte; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import com.tonnguyen.livelotte.util.DateTimeUtil; import com.tonnguyen.livelotte.util.NotificationUtil; import com.tonnguyen.livelotte.view.ResultViewGroup; import com.tonnguyen.livelotte.view.ResultViewPager; import com.tonnguyen.livelotte.view.ResultViewPagerAdapter; public class HomeActivity extends BaseActivity { private static final String TAG = "HomeActivity"; private static final String SESSION_KEY = "HomeActivity::SESSION_KEY"; public static final int DIALOG_DOWNLOAD_PROGRESS = 5; private ProgressDialog progressDialog; //private boolean isShowingDialog; private ResultViewPagerAdapter resultsAdapter; private ResultViewPager viewPager; //private TextView resultDate; private int currentDayIndex = 0; //private boolean isFirstLoad = false; private Handler threadHandler; // handler to process result reload request in Live mode private boolean isThreadExecuting = false; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // close any existing notification NotificationUtil.dismiss(this); // make sure our service has been running, to the result auto update function will work if (context.isAutoUpdateEnable()) { LiveLotteService.startIfNotRunning(context); } setContentView(R.layout.main); //resultDate = (TextView)findViewById(R.id.home_resultDate); resultsAdapter = new ResultViewPagerAdapter(context); viewPager = (ResultViewPager) findViewById(R.id.resultPager); viewPager.setAdapter(resultsAdapter); viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { currentDayIndex = position; // TODO need to implement code to get resultView group from currentDayIndex, in order to be able to refresh it // when clicking on refresh menu button } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageScrollStateChanged(int state) { } }); ((Button) findViewById(R.id.home_previousDay)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { previous(); } }); ((Button) findViewById(R.id.home_nextDay)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { next(); } }); // create thread handler for processing message from RemainingTimeUpdater threadHandler = new Handler() { @Override public void handleMessage(Message msg) { processMessage(); super.handleMessage(msg); } }; initAdMob(); if (savedInstanceState == null) { //isFirstLoad = true; // mark this as true, to enable result fall back (show previous day's result in case today's result is null) //today = DateTimeUtil.getCalendar(); //currentDayIndex = 0; //executeGetResultTaskForToday(); // Result result = getResultForToday(); // if(result == null) { // result was not available for today // Log.d(TAG, "Result for today is not available at the moment, getting yesterday result instead"); // // get yesterday result // // Subtract 1 day // currentDayIndex--; // Log.d(TAG, "currentDayIndex = " + currentDayIndex); // today.add(Calendar.DATE, -1); // result = ResultUtil.getResult(context, today); // bindData(result, today); // } else { // bindData(result, today); // } } // else: will be processed in onRestoreInstanceState // // TODO test // try { // Log.d(TAG, "Start test***************************"); // // test current time in live mode: // Calendar date = DateTimeUtil.getCalendar(); // date.set(Calendar.HOUR_OF_DAY, 19); // date.set(Calendar.MINUTE, 20); // if (!DateTimeUtil.isLiveModeRequest(date)) { // throw new Exception("This must be Live mode : " + DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime())); // } else { // Log.d(TAG, DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime()) + " isLiveModeRequest"); // } // // date.set(Calendar.HOUR_OF_DAY, 19); // date.set(Calendar.MINUTE, 10); // if (DateTimeUtil.isLiveModeRequest(date)) { // throw new Exception("This must not be Live mode : " + DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime())); // } else { // Log.d(TAG, DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime()) + " is not LiveModeRequest"); // } // // date.set(Calendar.HOUR_OF_DAY, 19); // date.set(Calendar.MINUTE, 35); // if (DateTimeUtil.isLiveModeRequest(date)) { // throw new Exception("This must not be Live mode : " + DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime())); // } else { // Log.d(TAG, DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime()) + " is not LiveModeRequest"); // } // // // test isBeforeRollingTime // date.set(Calendar.HOUR_OF_DAY, 19); // date.set(Calendar.MINUTE, 10); // if (!DateTimeUtil.isBeforeRollingTime(date)) { // throw new Exception("This time must be before 19h15 : " + DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime())); // } else { // Log.d(TAG, DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime()) + " isBeforeRollingTime"); // } // // // test isBeforeRollingTime // date.set(Calendar.HOUR_OF_DAY, 19); // date.set(Calendar.MINUTE, 25); // if (!DateTimeUtil.isBeforeRollingEndTime(date)) { // throw new Exception("This time must be before 19h30 : " + DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime())); // } else { // Log.d(TAG, DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime()) + " isBeforeRollingEndTime"); // } // // // test isAfterRollingTimeOut // date.set(Calendar.HOUR_OF_DAY, 19); // date.set(Calendar.MINUTE, 46); // if (!DateTimeUtil.isAfterRollingTimeOut(date)) { // throw new Exception("This time must be after 19h45 : " + DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime())); // } else { // Log.d(TAG, DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime()) + " isAfterRollingTimeOut"); // } // // // isAfterRollingTime // date.set(Calendar.HOUR_OF_DAY, 19); // date.set(Calendar.MINUTE, 32); // if (!DateTimeUtil.isAfterRollingTime(date)) { // throw new Exception("This time must be after 19h30 : " + DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime())); // } else { // Log.d(TAG, DateTimeUtil.SIMPLE_DATE_TIME_FORMAT.format(date.getTime()) + " isAfterRollingTime"); // } // } catch (Exception e) { // Log.e(TAG, e.toString() + " *************************"); // } finally { // Log.d(TAG, "End test***************************"); // } // Test for Lunar calendar // int[] value = LunarCalendarUtil.Solar2Lunar(today.get(Calendar.DAY_OF_MONTH), today.get(Calendar.MONTH) + 1, today.get(Calendar.YEAR)); // Log.d(TAG, "Am lich: **************** " + value[0] + "-" + value[1] + "-" + value[2]); } @Override public void onResume() { super.onResume(); // Log.d(TAG, "onResume, currentDayIndex=" + currentDayIndex + ", isFirstLoad = " + isFirstLoad); // Calendar currentDate = DateTimeUtil.getCalendar(); boolean isLiveModeRequest = DateTimeUtil.isLiveModeRequest(DateTimeUtil.getCalendar()); Log.d(TAG, "onResume, isLiveModeRequest=" + isLiveModeRequest); if (isLiveModeRequest) { Log.d(TAG, "onResume, starting thread to auto update result"); startResultUpdaterThread(); } // // // avoid duplicate result requests by checking isFirstLoad flag. If isFirstLoad == true, result will be requested in onCreate // if(!isFirstLoad && currentDayIndex == 0) { // viewing today's result // if(context.isAutoUpdateEnable() && context.isLiveModeEnable() && isLiveModeRequest) { // // in Live mode, reload result for today, get it from DB // Log.d(TAG, "in Live mode, reload result for today, get it from DB"); // ResultDownloader downloadTask = new ResultDownloader(this, context, false); // downloadTask.execute(currentDate); // } else { // // reload data from live source // Log.d(TAG, "reload data from live source"); // executeGetResultTaskForToday(); // } // } // close any existing notification NotificationUtil.dismiss(this); } // /** // * Override the onCreateDialog, show when async task was working, user leaved application, // * and came back, Android will know what dialog should be displayed // */ // @Override // protected Dialog onCreateDialog(int id) { // Log.d(TAG, "onCreateDialog " + id); // if(progressDialog != null && progressDialog.isShowing()) { // progressDialog.dismiss(); // progressDialog = null; // } // switch (id) { // case DIALOG_DOWNLOAD_PROGRESS: // progressDialog = new ProgressDialog(this); // progressDialog.setMessage(context.getString(R.string.download_Resource_Message_Downloading)); // progressDialog.setCancelable(false); // break; // default: // break; // } // //isShowingDialog = true; // return progressDialog; // } // private void executeGetResultTask(Calendar dateToGet) { // ResultDownloader downloadTask = new ResultDownloader(this, context); // downloadTask.execute(dateToGet); // } // // private void executeGetResultTaskForToday() { // executeGetResultTask(DateTimeUtil.getCalendar()); // } /** * Create option menu */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } /** * Process when user click on option menu */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_preference: startActivity(new Intent(context, Preferences.class)); return true; case R.id.menu_refresh: Log.d(TAG, "currentDayIndex = " + currentDayIndex); ((ResultViewGroup) (viewPager.getChildAt(currentDayIndex))).refresh(); return true; default: return super.onOptionsItemSelected(item); } } private void previous() { // Subtract 1 day currentDayIndex--; Log.d(TAG, "currentDayIndex = " + currentDayIndex); // today.add(Calendar.DATE, -1); // executeGetResultTask(today); viewPager.setCurrentItem(currentDayIndex); } private void next() { //if(currentDayIndex < 0) { // add 1 day currentDayIndex++; Log.d(TAG, "currentDayIndex = " + currentDayIndex); // today.add(Calendar.DATE, 1); // executeGetResultTask(today); //bindData(ResultUtil.getResult(context, today), today); //} viewPager.setCurrentItem(currentDayIndex); } // private void bindData(Result result, Calendar date) { // Log.d(TAG, "bindData"); // String dateString = toSimpleDateString(date.getTime()); // resultDate.setText(dateString); // resultViewGroup.setResult(result, date, dateString); // } // private String toSimpleDateString(Date date) { // return DateTimeUtil.SIMPLE_DATE_FORMAT.format(date); // } @Override protected void onPause() { super.onPause(); stopResultUpdaterThread(); } @Override protected void onStop() { super.onStop(); stopResultUpdaterThread(); } private void stopResultUpdaterThread() { // stop UI result update thread isThreadExecuting = false; } private void startResultUpdaterThread() { if (context.isAutoUpdateEnable()) { isThreadExecuting = true; new LiveModeResultUpdater().start(); } } @Override protected void onSaveInstanceState(Bundle state) { Log.d(TAG, "onSaveInstanceState " + state.toString()); // stop UI result update thread stopResultUpdaterThread(); // save the current session, so next time when user come back, we will load it Log.d(TAG, "storing currentDayIndex: " + currentDayIndex); state.putInt(SESSION_KEY, currentDayIndex); super.onSaveInstanceState(state); } @Override protected void onRestoreInstanceState(Bundle state) { Log.d(TAG, "onRestoreInstanceState " + state.toString()); // restore the last session of user currentDayIndex = state.getInt(SESSION_KEY, 0); Log.d(TAG, "got currentDayIndex: " + currentDayIndex); // today = DateTimeUtil.getCalendar(); // today.add(Calendar.DATE, currentDayIndex); // //bindData(ResultUtil.getResult(context, today), today); // executeGetResultTask(today); viewPager.setCurrentItem(currentDayIndex); super.onRestoreInstanceState(state); } /** * ask thread handler to reload result */ private void askThreadHandlerToUpdateResult() { Message msg = new Message(); msg.what = 1; // whatever threadHandler.sendMessage(msg); } /** * Thread handler will process message here, to process reload result request * @param msg * @param application */ private void processMessage() { ((ResultViewGroup) (viewPager.getChildAt(currentDayIndex))).refresh(); } /** * A thread to update result in Live Mode (only get result from DB) * @author Ton Nguyen * */ private class LiveModeResultUpdater extends Thread { private static final long ONE_SECOND = 1000; /** * Create an instance of remaining time updater. */ public LiveModeResultUpdater() { } /** * Thread's start point */ public void run() { doWork(); } /** * Update remaining time while user is in exam */ private void doWork() { while (isThreadExecuting && DateTimeUtil.isLiveModeRequest(DateTimeUtil.getCalendar())) { if (currentDayIndex == 0) { Log.d(TAG + " - LiveModeResultUpdater", "getting result from DB, in Live mode"); askThreadHandlerToUpdateResult(); } try { sleep(ONE_SECOND * 10); // 10 seconds } catch (InterruptedException e) { } } Log.d(TAG + " - LiveModeResultUpdater", "LiveModeResultUpdater has been destroyed"); } } }