記得在2013年12月的時候,有系列文章是介紹怎么開發一個智能手表的app,讓用戶可以在足球比賽中記錄停表時間。隨著android wear的問世,在可穿戴設備中開發一款這樣的app確實是個很不錯的想法,但是按照目前對于android wear的架構了解來說,似乎有些困難。所以本系列文章我們就重寫這個應用,帶領大家進入android wear的世界。
本文不會長篇大論地講解我們要開發的這款app的用途,因為我們在之前的系列文章已經深入了解過了。這么說吧,這是一個計時類應用,在比賽開始的時候開始執行,在比賽的過程中可以暫停(停表),然后45分鐘過去后會有震動提醒,然后比賽進行45分鐘后也會有提醒。
在開始之前,很有必要先看看我們為什么要重寫這個app而不是直接上代碼。智能手表使用的是一個修改版的android1.6的系統,所以它的架構很像一個運行android1.6的手機,所以我們的app基于一個activity,我們所有的工作都運行在這個activity上。在開始學習智能手表開發之前,我們必須很清楚地知道,我們之前的設計在android wear上并不適用,盡管它也是支持activity,但是在android wear上工作方式是不同的。在手機或者平板上,如果一個activity從sleep狀態回到喚醒狀態,activity會被重新喚醒,但是在wear上卻不是這樣。一段時間過去后wear設備會進入sleep,但是在設備喚醒后,處于sleep狀態的activity卻不會再被喚醒了。
首先這個問題使我非常驚訝,我一直很想知道activity有了這個限制后,還能開發實用的app嗎?后來才發現這個問題完全是多慮的,我漸漸地發現,要開發一個實用的app也很簡單——我們只需要轉變我們的軟件設計模式,使它更符合android wear的體系結構,而不是當做一個手機來看。
這里我們需要考慮的最基本的問題是,這個計時應用程序需要基于一個一直運行的服務來記錄時間。但是基于長運行的服務不是一個好的方案,因為它會耗電。這里我們提到的記錄時間這個關鍵詞,也就是說,我們并不需要真的實現一個長運行的服務,只要在用戶需要看的時候我們可以更新消息顯示就行。在大部分的時間里,其實用戶只需要了解大概過去了多長時間,只有在比賽暫停或者中場快結束的時候才需要顯示更詳細的信息。所以在大部分的時間里,我們只需要顯示精確到分鐘即可,然后在用戶需要的時候才精確到秒。
我們要實現這個方法的基本方法就是使用alarmmanager每分鐘觸發一次更新通知事件,去更新分鐘顯示。這個通知事件還包括顯示精確到秒的activity,但是只有在用戶滑動屏幕的時候才會顯示整個通知。通過這種方式我們可以在必須顯示的時候才去更新消息,所以對大部分設備來說,每分鐘更新一次消息顯示比一直運行一個服務更加省電。
下圖顯示充分證明了這點,首先我們需要打開通知,這樣就可以得到精確到秒的顯示了。
然而,在有信息顯示或者設備休眠的時候,我們只需要顯示精確到分鐘就可以了。
有一件事情需要說明一下,就是這個app的名字已經改變了。之前在在i'm watch的版本上叫做“footy timer”,現在改為“match timer”。因為在使用語音啟動app的時候,google的聲音識別對“footy”這個詞很不敏感,我們用“ok google,start footy timer”這個命令不能啟動應用,而使用“ok google,start match timer”就可以使用。
最后,很抱歉這篇文章沒有代碼,但是本系列文章會稍微有些變動。以前本人會在每篇文章末尾附上文章相關的代碼段,這個請放心,之后的文章還是會這樣的,因為這個是一個功能完善的app,而不是系列技術文章,所以在接下來的文章會包含一些代碼示例和注釋,在本系列文章完結的時候會附上整個項目的源碼。
match timer 可以在google play上找到:https://play.google.com/store/apps/details?id=com.stylingandroid.matchtimer
上面我們解釋了為什么要在android wear重寫這個計時器app(因為之前已經在“i'm watch”里面開發過了),下面我們就來看看代碼。
我們以這個app的一個核心類開始,這個類負責控制計時器的狀態。這個類包含了4個long類型的變量:第一個代表計時器開始的時間;第二個代表計時器停止的時間(在運行中的話,它就是0);第三個代表計時器停表的時間(如果當前沒有停表,那它也是0),第四個代表總共停表的時長。通過這四個變量我們就可以維持計時器的狀態了,還可以通過計算得到我們需要展示的其他信息。這個類的基本功能就是都是為了操作這些變量,即維持計時器的這些狀態。
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
|
public final class matchtimer { . . . public static final int minute_millis = 60000 ; private long start; private long currentstoppage; private long totalstoppages; private long end; . . . public long getelapsed() { if (isrunning()) { return system.currenttimemillis() - start; } if (end > 0 ) { return end - start; } return 0 ; } public boolean isrunning() { return start > 0 && end == 0 ; } public boolean ispaused() { return currentstoppage > 0 ; } public int getelapsedminutes() { return ( int ) ((system.currenttimemillis() - start) / minute_millis); } public long gettotalstoppages() { long now = system.currenttimemillis(); if (ispaused()) { return totalstoppages + (now - currentstoppage); } return totalstoppages; } public long getplayed() { return getelapsed() - gettotalstoppages(); } public long getstarttime() { return start; } . . . } |
這些都是基本的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
|
public final class matchtimer { . . . public void start() { if (end > 0 ) { start = system.currenttimemillis() - (end - start); end = 0 ; } else { start = system.currenttimemillis(); } save(); } public void stop() { if (ispaused()) { resume(); } end = system.currenttimemillis(); save(); } public void pause() { currentstoppage = system.currenttimemillis(); save(); } public void resume() { totalstoppages += system.currenttimemillis() - currentstoppage; currentstoppage = 0l; save(); } public void reset() { resetwithoutsave(); save(); } private void resetwithoutsave() { start = 0l; currentstoppage = 0l; totalstoppages = 0l; end = 0l; } } |
這些還是基本的java代碼,也可以不用講了。只有save()方法我們還沒有見到,這是在類的最后寫的,這個函數才值得的我們講講。
前一篇文章我們討論了關于喚醒機制的問題,我們不需要去維持一個長連接或者后臺服務,只需要維持這幾個計時器的狀態就可以了。我們使用sharedpreference來實現:
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
|
public final class matchtimer implements sharedpreferences.onsharedpreferencechangelistener { private static final string key_start = "com.stylingandroid.matchtimer.key_start" ; private static final string key_current_stoppage = "com.stylingandroid.matchtimer.key_current_stoppage" ; private static final string key_total_stoppages = "com.stylingandroid.matchtimer.key_total_stoppages" ; private static final string key_end = "com.stylingandroid.matchtimer.key_end" ; private static final string preferences = "matchtimer" ; private final sharedpreferences preferences; public static matchtimer newinstance(context context) { sharedpreferences preferences = context.getsharedpreferences(preferences, context.mode_private); long start = preferences.getlong(key_start, 0 ); long currentstoppage = preferences.getlong(key_current_stoppage, 0 ); long totalstoppages = preferences.getlong(key_total_stoppages, 0 ); long end = preferences.getlong(key_end, 0 ); return new matchtimer(preferences, start, currentstoppage, totalstoppages, end); } private matchtimer(sharedpreferences preferences, long start, long currentstoppage, long totalstoppages, long end) { this .preferences = preferences; this .start = start; this .currentstoppage = currentstoppage; this .totalstoppages = totalstoppages; this .end = end; } public void save() { preferences.edit() .putlong(key_start, start) .putlong(key_current_stoppage, currentstoppage) .putlong(key_total_stoppages, totalstoppages) .putlong(key_end, end) .apply(); } public void registerforupdates() { preferences.registeronsharedpreferencechangelistener( this ); } public void unregisterforupdates() { preferences.unregisteronsharedpreferencechangelistener( this ); } @override public void onsharedpreferencechanged(sharedpreferences sharedpreferences, string key) { long value = sharedpreferences.getlong(key, 0l); if (key.equals(key_start)) { start = value; } else if (key.equals(key_end)) { end = value; } else if (key.equals(key_current_stoppage)) { currentstoppage = value; } else if (key.equals(key_total_stoppages)) { totalstoppages = value; } } . . . } |
我們需要的就是newinstance()方法從sharedpreference中構造一個matchtimer實例,我們還需要save()方法,可以幫我們把當前的計時器狀態保存到sharedpreference中。
最后我們要說明的是,如果某一部分持有matchtimer對象的引用,但是其他對象已經改變了計時器的狀態,就可能會發生異常(見下一篇文章)。所以我們還需要提供一些方法去注冊和注銷matchtimer的實例,在sharedpreference的值改變時去接收計時器狀態的變化。
現在我們已經定義了一個基本的計時器了,下一篇文章我們會介紹怎么保持計時器的狀態以及在需要的時候去喚醒這些狀態。
match timer 可以在google play上下載:match timer.
在本系列前幾篇文章中,我們介紹了android wear計時器app,對設計思路和app的結構進行了分析。本文將講解如何定時喚醒程序提醒用戶。
對于為什么不用后臺服務的方式一直運行,我們已經進行了解釋——這種方式非常耗電。因此,我們必須要有一個定時喚醒機制。我們可以使用alarmmanager來實現這個機制,定時執行一個intent,然后通知broadcastreceiver。之所以選擇broadcastreceiver而不用intentservice,是因為我們要運行的任務是輕量級的而且生命周期非常短暫。使用broadcastreceiver可以避免每次執行任務的時候都經歷service的整個生命周期。因此,對于我們這種輕量級的任務來說非常合適——我們執行的任務都在毫秒級。
broadcastreceiver的核心在于onreceiver方法,我們需要在這里安排各種事件響應。
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
|
public class matchtimerreceiver extends broadcastreceiver { public static final int minute_millis = 60000 ; private static final long duration = 45 * minute_millis; private static final intent update_intent = new intent(action_update); private static final intent elapsed_alarm = new intent(action_elapsed_alarm); private static final intent full_time_alarm = new intent(action_full_time_alarm); private static final int request_update = 1 ; private static final int request_elapsed = 2 ; private static final int request_full_time = 3 ; public static void setupdate(context context) { context.sendbroadcast(update_intent); } . . . private void reset(matchtimer timer) { timer.reset(); } private void resume(context context, matchtimer timer) { timer.resume(); long playedend = timer.getstarttime() + timer.gettotalstoppages() + duration; if (playedend > system.currenttimemillis()) { setalarm(context, request_full_time, full_time_alarm, playedend); } } private void pause(context context, matchtimer timer) { timer.pause(); cancelalarm(context, request_full_time, full_time_alarm); long elapsedend = timer.getstarttime() + duration; if (!isalarmset(context, request_elapsed, elapsed_alarm) && elapsedend > system.currenttimemillis()) { setalarm(context, request_elapsed, elapsed_alarm, elapsedend); } } private void stop(context context, matchtimer timer) { timer.stop(); cancelalarm(context, request_update, update_intent); cancelalarm(context, request_elapsed, elapsed_alarm); cancelalarm(context, request_full_time, full_time_alarm); } private void start(context context, matchtimer timer) { timer.start(); long elapsedend = timer.getstarttime() + duration; setrepeatingalarm(context, request_update, update_intent); if (timer.gettotalstoppages() > 0 && !timer.ispaused()) { long playedend = timer.getstarttime() + timer.gettotalstoppages() + duration; if (playedend > system.currenttimemillis()) { setalarm(context, request_full_time, full_time_alarm, playedend); } if (elapsedend > system.currenttimemillis()) { setalarm(context, request_elapsed, elapsed_alarm, elapsedend); } } else { if (elapsedend > system.currenttimemillis()) { setalarm(context, request_full_time, full_time_alarm, elapsedend); } } } . . . } |
代碼還是非常直觀易于理解的。首先實例化一個matchtimer對象(從sharedpreference中讀取數據),然后分別傳給對應的事件處理handler。之后等待動作發生,最后更新notification。
這里會處理8個事件動作,其中5個負責控制計時器的狀態(start、stop、pause、resume、reset);一個負責更新notification,剩下兩個負責到45分鐘喚醒后震動提示。
我們先從這幾個控制狀態開始:
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
|
public class matchtimerreceiver extends broadcastreceiver { public static final int minute_millis = 60000 ; private static final long duration = 45 * minute_millis; private static final intent update_intent = new intent(action_update); private static final intent elapsed_alarm = new intent(action_elapsed_alarm); private static final intent full_time_alarm = new intent(action_full_time_alarm); private static final int request_update = 1 ; private static final int request_elapsed = 2 ; private static final int request_full_time = 3 ; public static void setupdate(context context) { context.sendbroadcast(update_intent); } . . . private void reset(matchtimer timer) { timer.reset(); } private void resume(context context, matchtimer timer) { timer.resume(); long playedend = timer.getstarttime() + timer.gettotalstoppages() + duration; if (playedend > system.currenttimemillis()) { setalarm(context, request_full_time, full_time_alarm, playedend); } } private void pause(context context, matchtimer timer) { timer.pause(); cancelalarm(context, request_full_time, full_time_alarm); long elapsedend = timer.getstarttime() + duration; if (!isalarmset(context, request_elapsed, elapsed_alarm) && elapsedend > system.currenttimemillis()) { setalarm(context, request_elapsed, elapsed_alarm, elapsedend); } } private void stop(context context, matchtimer timer) { timer.stop(); cancelalarm(context, request_update, update_intent); cancelalarm(context, request_elapsed, elapsed_alarm); cancelalarm(context, request_full_time, full_time_alarm); } private void start(context context, matchtimer timer) { timer.start(); long elapsedend = timer.getstarttime() + duration; setrepeatingalarm(context, request_update, update_intent); if (timer.gettotalstoppages() > 0 && !timer.ispaused()) { long playedend = timer.getstarttime() + timer.gettotalstoppages() + duration; if (playedend > system.currenttimemillis()) { setalarm(context, request_full_time, full_time_alarm, playedend); } if (elapsedend > system.currenttimemillis()) { setalarm(context, request_elapsed, elapsed_alarm, elapsedend); } } else { if (elapsedend > system.currenttimemillis()) { setalarm(context, request_full_time, full_time_alarm, elapsedend); } } } . . . } |
這些方法主要有兩個功能:首先設置matchtimer的狀態,然后設置時間提醒的鬧鈴,改變參數就可以播放鬧鈴。這個功能還可以封裝成一個工具方法,叫setupdate()。這樣外部也可以觸發計時器的更新。
我們使用標準alarmmanager的方法來設置鬧鈴:
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
|
public class matchtimerreceiver extends broadcastreceiver { . . . public static final int minute_millis = 60000 ; . . . private void setrepeatingalarm(context context, int requestcode, intent intent) { alarmmanager alarmmanager = (alarmmanager) context.getsystemservice(context.alarm_service); pendingintent pendingintent = pendingintent.getbroadcast(context, requestcode, intent, pendingintent.flag_update_current); alarmmanager.setrepeating(alarmmanager.rtc_wakeup, system.currenttimemillis(), minute_millis, pendingintent); } private boolean isalarmset(context context, int requestcode, intent intent) { return pendingintent.getbroadcast(context, requestcode, intent, pendingintent.flag_no_create) != null ; } private void setalarm(context context, int requestcode, intent intent, long time) { alarmmanager alarmmanager = (alarmmanager) context.getsystemservice(context.alarm_service); pendingintent pendingintent = pendingintent.getbroadcast(context, requestcode, intent, pendingintent.flag_update_current); alarmmanager.setexact(alarmmanager.rtc_wakeup, time, pendingintent); } private void cancelalarm(context context, int requestcode, intent intent) { pendingintent pendingintent = pendingintent.getbroadcast(context, requestcode, intent, pendingintent.flag_no_create); if (pendingintent != null ) { alarmmanager alarmmanager = (alarmmanager) context.getsystemservice(context.alarm_service); alarmmanager.cancel(pendingintent); pendingintent.cancel(); } } . . . } |
這里值得討論的是setrepeatingalarm()這個方法。因為在wear在實現方式上有點不一樣。我們會在start事件中每秒鐘觸發一次鬧鈴更新notification動作,所以這里需要記錄具體已經過去了多少分鐘。正常來說我們會每隔60秒觸發一次這個動作,但是在wear上不能這么做。原因是——當設備在喚醒著的時候可以這樣做,但是如果設備進入睡眠狀態就需要重新計算下一分鐘的邊界值。這就需要異步更新部件,然后設備只需要每分鐘喚醒一次。一分鐘結束后在計時器需要更新狀態的時候觸發操作。
對于我們的計時器應用來說,顯示的分鐘數會比實際時間少1分鐘。但是顯示分鐘并不要求非常實時(但顯示秒數時需要非常精確),所以我們可以這樣操作:
完整的alarm handler是這樣使用振動服務的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class matchtimerreceiver extends broadcastreceiver { . . . private static final long [] elapsed_pattern = { 0 , 500 , 250 , 500 , 250 , 500 }; private static final long [] full_time_pattern = { 0 , 1000 , 500 , 1000 , 500 , 1000 }; private void elapsedalarm(context context) { vibrator vibrator = (vibrator) context.getsystemservice(context.vibrator_service); vibrator.vibrate(elapsed_pattern, - 1 ); } private void fulltimealarm(context context) { vibrator vibrator = (vibrator) context.getsystemservice(context.vibrator_service); vibrator.vibrate(full_time_pattern, - 1 ); } . . . } |
最后,我們通過這個方法來構造notification然后呈現給用戶:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class matchtimerreceiver extends broadcastreceiver { public static final int notification_id = 1 ; . . . private void updatenotification(context context, matchtimer timer) { notificationbuilder builder = new notificationbuilder(context, timer); notification notification = builder.buildnotification(); notificationmanagercompat notificationmanager = notificationmanagercompat.from(context); notificationmanager.notify(notification_id, notification); } } |
notification是wear計時器的一個重要的部分,這里還需要一個自定義類來構造這些notification通知。下一篇文章我們會講如何在計時器app中使用notification。
match timer可以在google play上下載:match timer。