-
Notifications
You must be signed in to change notification settings - Fork 4
/
Main.java
537 lines (446 loc) · 14.9 KB
/
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
package com.midlandroid.apps.android.laptimer;
import java.text.NumberFormat;
import com.midlandroid.apps.android.laptimer.background.BackgroundSrvc;
import com.midlandroid.apps.android.laptimer.background.timers.TimerUpdateUIListener;
import com.midlandroid.apps.android.laptimer.background.timers.TimerMode.RunningState;
import com.midlandroid.apps.android.laptimer.util.ServiceCommand;
import com.midlandroid.apps.android.laptimer.util.TextUtil;
import com.midlandroid.apps.android.laptimer.util.UIUtil;
import com.midlandroid.apps.android.laptimer.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity implements TimerUpdateUIListener {
private static final String LOG_TAG = Main.class.getSimpleName();
// Views
private Button startStopBtn;
private Button lapNumBtn;
private TextView lapTimeTxt;
private TextView currTimeTxt;
private TextView timerHistoryTxt;
private MenuItem saveHistoryMI;
// members
private long currTime;
private long lapTime;
private int lapCount;
private NumberFormat numFormat;
private Messenger myMessenger;
/////////////////////////////////////////////////
// Overridden Android Activities Methods
/////////////////////////////////////////////////
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create the background service
startService(new Intent(this, BackgroundSrvc.class));
// initialize the variables
numFormat = NumberFormat.getInstance();
numFormat.setMinimumIntegerDigits(2);
numFormat.setMaximumIntegerDigits(2);
numFormat.setParseIntegerOnly(true);
myMessenger = new Messenger(myHandler);
currTime = lapTime = 0;
lapCount = 1;
// Lap time text view
lapTimeTxt = (TextView)findViewById(R.id.lap_timer_txt);
lapTimeTxt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (boundService.getAppPreferences().getUseOneClickTextCopy())
_addViewTextToClipBoard(v);
}
});
// Lap increment button
lapNumBtn = (Button)findViewById(R.id.lap_increment_btn);
lapNumBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
_lapIncrement();
}
});
// Current Time text view
currTimeTxt = (TextView)findViewById(R.id.timer_counter_txt);
currTimeTxt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (boundService.getAppPreferences().getUseOneClickTextCopy())
_addViewTextToClipBoard(v);
}
});
// Timer Start Stop Button
startStopBtn = (Button)findViewById(R.id.timer_start_stop_btn);
startStopBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
_startStopTimer();
}
});
// Timer History Text View
timerHistoryTxt = (TextView)findViewById(R.id.lap_txt);
timerHistoryTxt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (boundService != null && boundService.getAppPreferences().getUseOneClickTextCopy())
_addViewTextToClipBoard(v);
}
});
}
@Override
public void onResume() {
super.onResume();
// Attach to the service
_doBindService();
}
@Override
public void onPause() {
super.onPause();
// Disconnect from the service
_doUnbindService();
}
@Override
public void onDestroy() {
super.onDestroy();
// Terminate the service if the application is being destroyed.
stopService(new Intent(this, BackgroundSrvc.class));
}
/////////////////////////////////
// Overridden controls
/////////////////////////////////
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
_setMenuItemEnabledBasedOnRunState();
}
else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP && boundService != null && boundService.getAppPreferences().getUseVolumeButtonsForTimer()) {
_startStopTimer();
return true;
}
else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN && boundService != null && boundService.getAppPreferences().getUseVolumeButtonsForTimer()) {
_lapIncrement();
return true;
}
return super.onKeyDown(keyCode, event);
}
////////////////////////////////////
// Options Menu
////////////////////////////////////
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.timer_menu, menu);
// Get the references to the items that will be mode
// based on the app's run state.
saveHistoryMI = menu.findItem(R.id.mi_save_timer_history);
_setMenuItemEnabledBasedOnRunState();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.mi_reset_timer:
_resetTimer();
return true;
case R.id.mi_save_timer_history:
_saveTimerHistory();
return true;
case R.id.mi_timer_history:
_showTimerHistory();
return true;
case R.id.mi_preferences:
_showPreferences();
return true;
}
return false;
}
////////////////////////////////////
// User Action Handler Methods
////////////////////////////////////
/**
* Notifies the background service that the user has selected
* to start or stop the timer.
*/
private void _startStopTimer() {
_msgTimerService(ServiceCommand.CMD_START_STOP_TIMER);
}
/**
* Notifies the background service that the lap count should
* be incremented.
*/
private void _lapIncrement() {
_msgTimerService(ServiceCommand.CMD_LAP_INCREMENT);
}
/**
* Resets the timer. If the user has specified to be warned when
* reseting the timer prompt them instead.
*/
private void _resetTimer() {
if (boundService != null && boundService.getAppPreferences().getUseSecondChanceReset()) {
_showPromptToResetTimer();
} else {
_doResetTimer();
}
}
/**
* Notifies the background service that the timer should be stopped
* and reseted.
*/
private void _doResetTimer() {
_msgTimerService(ServiceCommand.CMD_RESET_TIMER);
}
/**
* Notifies the background service that this UI needs to be updated.
*/
private void _refreshUI() {
_msgTimerService(ServiceCommand.CMD_REFRESH_MAIN_UI);
}
////////////////////////////////////
// Private methods
////////////////////////////////////
/**
* Adds the text of the provided view to the android system's
* clip board buffer.
* @param v View with text to be added to the clip board
*/
private void _addViewTextToClipBoard(View v) {
ClipboardManager clipboard =
(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(((TextView)v).getText());
Toast t = Toast.makeText(this, R.string.text_copied_to_clipboard_toast, Toast.LENGTH_SHORT);
t.show();
}
/**
* Using the state of the background service the menu items are
* enabled or disabled.
*/
private void _setMenuItemEnabledBasedOnRunState() {
BackgroundSrvc srvc = boundService;
if (srvc != null && saveHistoryMI != null /*&& timerModeMI != null*/) {
RunningState state = srvc.getTimerState();
if (state == RunningState.RUNNING || state == RunningState.RESETTED)
saveHistoryMI.setEnabled(false);
else
saveHistoryMI.setEnabled(true);
}
}
/**
* Creates and sends a message to the background service.
* @param cmd Message id
*/
private void _msgTimerService(final int cmd) {
_msgTimerService(cmd, null);
}
/**
* Creates and sends a message to the background service with
* the provided pay load
* @param cmd Message id
* @param payload Data to be send to background service
*/
private void _msgTimerService(final int cmd, final Object payload) {
if (boundService != null) {
Message msg = myHandler.obtainMessage();
msg.what = cmd;
msg.obj = payload;
msg.replyTo = myMessenger;
try {
boundService.myMessenger.send(msg);
} catch (RemoteException e) {
Log.e(LOG_TAG, "Failed to message background service", e);
}
}
}
/**
* Prompts the user if they are sure they really want to
* reset the current timer.
*/
private void _showPromptToResetTimer() {
UIUtil.showAlertPrompt(this,
"Confirm Timer Reset",
"Are you sure you want to reset the timer?",
"Yes", "No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInf, int which) {
if (DialogInterface.BUTTON_POSITIVE == which) {
_doResetTimer();
} else if (DialogInterface.BUTTON_NEGATIVE == which) {
// Cancel, nothing to do.
}
}
});
}
/**
* Instructs the timer to save the current timer history.
*/
private void _saveTimerHistory() {
_msgTimerService(ServiceCommand.SAVE_TIMER_HISTORY);
}
/**
* Displays the timer history UI to the user.
*/
private void _showTimerHistory() {
Intent i = new Intent(this, TimerHistory.class);
startActivity(i);
}
/**
* Displays the Android Preferences UI to the user.
*/
private void _showPreferences() {
Intent i = new Intent(this, Preferences.class);
startActivity(i);
}
//////////////////////////////////////
// Service Controls
//////////////////////////////////////
private boolean isSrvcbound = false;
private BackgroundSrvc boundService;
private ServiceConnection srvcConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
boundService = ((BackgroundSrvc.LocalBinder)service).getService();
// Provide the bound service with our timer UI listener
boundService.setUpdateUIListener(Main.this);
// Update the app's default shared preferences
_updateAppPreferences();
// Refresh the UI's views
_refreshUI();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
boundService = null;
}
};
/**
* Create a connection to the background service.
*/
private void _doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(this,
BackgroundSrvc.class), srvcConnection, Context.BIND_AUTO_CREATE);
isSrvcbound = true;
}
/**
* Tell the service to update it's preferences
*/
private void _updateAppPreferences() {
if (isSrvcbound && boundService != null)
boundService.updateAppPreferences();
}
/**
* Remove the connection to the background service.
*/
private void _doUnbindService() {
if (isSrvcbound) {
// Detach our existing connection.
unbindService(srvcConnection);
isSrvcbound = false;
}
}
///////////////////////////////////
// Message Handler
///////////////////////////////////
private Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
default:
break;
}
}
};
////////////////////////////////////
// Timer Service UI Update Listeners
////////////////////////////////////
@Override
public void setCurrentTime(final long currTime) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
currTimeTxt.setText(TextUtil.formatDateToString(currTime, numFormat));
Main.this.currTime = currTime;
}
});
}
@Override
public void setLapTime(final long lapTime) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
lapTimeTxt.setText(TextUtil.formatDateToString(lapTime, numFormat));
Main.this.lapTime = lapTime;
}
});
}
@Override
public void setLapCount(final int count) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
// The lap count is 0 based and needs to be offset for
// the user.
lapCount = count+1;
// Update the UI from the value provided.
lapNumBtn.setText("Lap "+ Integer.toString(lapCount));
}
});
}
@Override
public void resetUI() {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
// Reset current timer and update text
currTime = 0;
currTimeTxt.setText(TextUtil.formatDateToString(currTime, numFormat));
// Reset lap timer and update text
lapTime = 0;
lapTimeTxt.setText(TextUtil.formatDateToString(lapTime, numFormat));
// Reset the timer history and update UI
timerHistoryTxt.setText("");
// Reset the lap count, and update the lap button
lapCount = 1;
lapNumBtn.setText("Lap "+ Integer.toString(lapCount));
}
});
}
@Override
public void setTimerHistory(final String history) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
// Reset the timer history and update UI
timerHistoryTxt.setText(history);
}
});
}
}