android SyncAdapter中的异步齐射调用

时间:2016-01-26 08:21:58

标签: android multithreading asynchronous concurrency android-syncadapter

我使用volley库实现了SyncAdapter。它正在工作,但后来我意识到Iam从onPerformSync方法调用异步(排球请求)代码。

  • Q1:coudl onPerformSync并行执行多次? (对于一个用户/一个权限)。我需要编写内码安全吗?用锁?同步? SyncAdapter本身不是同步的,所以任何内部同步都没用吗?
  • Q2:是onPerformSync线程安全,哪个线程?在我看来,所有onPerformSync调用都是由相同的线程引用完成的。这是否意味着SyncAdapter实际上被系统多次重用?
  • 问题3:在同步代码完成之前结束onPerformSync是否安全? (凌空调用可能比创建抽射请求,运行并完成更长时间)
    @Override
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient contentProviderClient, SyncResult syncResult) {
        JsonObjectRequest jsObjRequest = new JsonObjectRequest
                (Request.Method.GET, url, null, new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // time consuming code
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub
                    }
                });
        // Access the RequestQueue through your singleton class.
        MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
        // onPerformSync end reached before volley request processing ends
    }

1 个答案:

答案 0 :(得分:0)

您可以使用CountDownLatch ,但我读过,这不是在同步适配器中实现它对我有用的好方法

    
    private CountDownLatch doneSignal = new CountDownLatch(1);
    
    @Override
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient contentProviderClient, SyncResult syncResult) {
        JsonObjectRequest jsObjRequest = new JsonObjectRequest
                (Request.Method.GET, url, null, new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // time consuming code
                        //put this line as the last line when everything is done
                        doneSignal.countDown();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub
                    }
                });
        // Access the RequestQueue through your singleton class.
        MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
        try {
            doneSignal.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // onPerformSync end reached before volley request processing ends
    }