android SyncAdapter中的异步齐射调用

Woo*_*off 6 concurrency multithreading android asynchronous android-syncadapter

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

  • Q1:coudl是onPerformSync并行多次执行?(对于一个用户/一个权限).我需要编写内码安全吗?用锁?同步?SyncAdapter本身不是同步的,所以任何内部同步都没用吗?
  • Q2:是onPerformSync线程安全,哪个线程?在我看来,所有onPerformSync调用都是由相同的线程引用完成的.这是否意味着SyncAdapter实际上被系统多次重用?
  • Q3:在同步代码完成之前结束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
    }
Run Code Online (Sandbox Code Playgroud)

Far*_*str 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
    }
Run Code Online (Sandbox Code Playgroud)