Androidã®AsyncTaskããã¹ããã¦ã¿ãã
Androidã®ãã¹ãã³ã¼ãæ¸ãã®ãæ¥èª²ã®ãããããã ãã
AsyncTaskã®ãã¹ãã³ã¼ãã®æ¸ãæ¹ãåãããªãã¦æ©ãã§ããã©ã解決çãè¦ã¤ãã£ãã®ã§ãã°ã«æ®ãã¾ããæè¦ã»ææã¨ãããã°ã³ã¡ã³ããé¡ããã¾ããã
AsyncTaskã¨ã¯
AsyncTaskã¯Androidã§ä½¿ãéåæå¦çã®ã¯ã©ã¹ã§ããéããå¦ç(ä¾ãã°HTTPã§ã®DLãç»åã®å¤æå¦çãªã©)ãããã¯ã°ã©ã¦ã³ãã§å®è¡ãããã®ã«åãã¦ã¾ããå¦çã®é²è¡ç¶æ³ãããã°ã¬ã¹ãã¼ã«è¡¨ç¤ºããããã¨ãã§ãã¾ãã
ä¼¼ãå¦çã«Serviceãããã¾ãããServiceã¯ããã¯ã°ã©ã¦ã³ãã§å¦çãç¹°ãè¿ããã(GPSãç£è¦ãç¶ãã¦ç¹å®ã®æ¡ä»¶ã§éç¥ãåºããªã©)ãªã©ãç®çãªã®ã§ãActivityããç¬ç«ãã¦ãã¾ãã
Activityã¨å¯æ¥ãªéåæå¦çãAsyncTaskãç¬ç«ããéåæå¦çãServiceã£ã¦æãã§ä½¿ãåãã¦ã¾ãã
Serviceã¯å°ç¨ã®TestCaseããããããããã©ãAsyncTaskã¯ç¡ãã®ã§ãã¦ã©ããããã®ãã
ãã¸ãã¯ã®ãã¹ã
ã¾ãã¯ãéåæã¨ãã©ãã§ãããã®ã§ãã¡ã½ããã®ãã¸ãã¯ã®ãã¹ãããããã§ããã§ãAsyncTaskã® #doInBackground() 㯠protected ãªã®ã§ã以ä¸ã®ããæ¹ã§ã¯åãã¾ããã
public class HogeAsyncTaskTest extends AndroidTestCase { public void testDoInBackground(){ HogeAsyncTask task = new HogeAsyncTask(); //protectedãªã®ã§ã³ã³ãã¤ã«ã¨ã©ã¼ //int result = task.doInBackground(0); } }
task.execute() ãã¡ããã¨éåæå¦çãèµ°ã£ã¡ãããHogeAsyncTask#doInBackground() ãpublicã«ããã°ããã®ã§ããããã¹ãã®ããã«ã³ã¼ããå¤ããã®ã¯ãã®å®è£
ã©ããã£ã¦æãã§ããããã¹ãã³ã¼ããåä¸ããã±ã¼ã¸åããã®ãã©ããã
ãã§ãè²ã
æ©ãã æå¥ããã¹ãç¨ã«HogeAsyncTask ãç¶æ¿ããã¯ã©ã¹ãä½ã£ã¦ããã®ã¯ã©ã¹ããã¹ããããã¨ã«ãã¾ããã
public class HogeAsyncTaskTest extends AndroidTestCase { public void testDoInBackground(){ HogeAsyncTaskExt task = new HogeAsyncTaskExt(); int result = task.doInBackground(0); assertEquals(1, result); } //ãã¹ã対象ã¨å®è³ªåãã¯ã©ã¹ //ã ãã©ãdoInBackgroundãpublicã«ãªã£ã¦ããã class HogeAsyncTaskExt extends HogeAsyncTask{ @Override public Integer doInBackground(Integer... params) { return super.doInBackground(params); } } }
ããã§ãdoInBackgroundã®ãã¹ããã§ãã¾ããããã£ãããã£ããã
ããã¾ã§ã¯ãAsyncTaskã®ãã¹ãæ¹æ³ã¨ãããããprotectedã¡ã½ããã®ãã¹ãã®ããæ¹ã§ããã次ã¯éåæå¦çã®ãã¹ãæ¹æ³ã§ãã
éåæã®ãã¹ã
éåæå¦çã®ãã¹ããªã®ã§ã AsyncTask ãçµãã£ãã®ãæ¤ç¥ãã¦ãã®çµæã調ã¹ããã§ããã§ããAsyncTaskã¯çµãã£ããã¨ãæãã¦ããã¾ãããããã§ãCountDownLatch ã¨ä¸è¨ã§ä½¿ã£ã HogeAsyncTask ãæ¡å¼µãã HogeAsyncTaskExt ãå©ç¨ãã¦ãã¹ããã¾ãã
public class HogeAsyncTaskTest extends AndroidTestCase { //ã«ã¦ã³ããã¦ã³ã管çããã¯ã©ã¹ãå¾ æ©ä¸ã«1åã«ã¦ã³ããããã¨å¦çãåéãããã CountDownLatch signal; @Override protected void setUp() throws Exception { super.setUp(); signal = new CountDownLatch(1); } public void testExecute() throws InterruptedException{ HogeAsyncTaskExt task = new HogeAsyncTaskExt(); task.execute(0); //ã«ã¦ã³ããã¦ã³ãçµããã¾ã§å¦çãæ¢ã¾ãã signal.await(); //ããã«assertã¨ãæ¸ãã¦ã } class HogeAsyncTaskExt extends HogeAsyncTask{ @Override //doInBackground()ã®å¾ã«å¼ã°ããå¦çã protected void onPostExecute(Integer result) { super.onPostExecute(result); //ã«ã¦ã³ããã¦ã³ãã¦ããã¹ãå¦çãåéãããã signal.countDown(); } } }
ã«ã¦ã³ãã1ã«ã»ãããã¦ãã¹ãå¦çãå®è¡ãã¦å¾
æ©ãexecuteã®å¦çãçµãã£ãã(onPostExecuteãå¼ã°ããã)å¾
æ©ç¶æ
ã解é¤ãã¦assertã¨ãã§çµæãå¤å®ããã
ãããªæãã®ã³ã¼ãã§ãã¹ããããã¨ãã§ãã¾ããããã£ããããã¡ããï¼