LoginSignup
10
12

More than 5 years have passed since last update.

Android Volleyを使った同期処理サンプル(InstrumentationTestCaseを使ったテストコード)

Posted at

Android Volleyを使った同期通信をテストコードで実相してみました。

実装中にどうしてもタイムアウトしちゃう所があって、その原因の追究のために作成したものなんですが、もしかしたらどなたかのお役にたつかもしれません。

Android Studioの「Run/Debug Configuration」で「Android Tests」を追加して頂ければ使えるはずです。
Contextの取得はこちらの記事を参考にさせていただきました。
http://qiita.com/amay077/items/e3741f6789d663b40183

同期処理についてはこちらを参考にさせてもらいました。
http://nice20blog.blogspot.jp/2014/01/volley.html

ちなみにStringRequestでなくても、JSONObjectRequestでも全然OKです。

/**
 * 
 */
public class VolleySyncTest extends InstrumentationTestCase {

    private static final String TAG = VolleySyncTest.class.getSimpleName();

    /**
     * ApplicationContext を取得します
     */
    private Context getApplicationContext() {
        return this.getInstrumentation().getTargetContext().getApplicationContext();
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }

    public void testVolleySync() {
        Context context = getApplicationContext();

        RequestQueue mQueue = Volley.newRequestQueue(context);

        String url = "https://www.google.co.jp/";
        //同期処理サンプル
        RequestFuture<String> f = RequestFuture.newFuture();
        StringRequest r= new StringRequest(Request.Method.GET, url, f, f);
        mQueue.add(r);
        mQueue.start();

        try {
            String string = f.get(15000, TimeUnit.MILLISECONDS);
            Log.i(TAG, string);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
10
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
12