如何用服务替换这个asynctasks和听众链?

时间:2015-04-14 14:01:24

标签: android android-asynctask

在我的应用程序中,当用户创建产品时,我会启动一系列数据库操作,网络操作和文件操作,这些操作都连接到活动并通过监听器。 虽然所有内容都在一个单独的AsyncTask中,但UI冻结。

我想知道如何将这种方法替换为在后台线程中处理所有这些内容的服务。

以下是一些示例代码:

public interface OnLogInUserToServerListener {
    void onLoginUserToServerSuccess(User user);
    void onLoginUserToServerFailure(String error);
}

public interface OnInsertProductInDBListener {
    void onInsertProductInDBSuccess(int productId);
    void onInsertProductInDBFailure();

}

// The rest of the interfaces follow the same pattern


public class InsertProductInDBAsync extends AsyncTask<Void, Void, Boolean> {

    private OnInsertProductInDBListener listener;

    public InsertProductInDBAsync (OnInsertProductInDBListener listener) {
        this.listener = listener;
    }

     boolean doInBackground {
         // do db insertion operation here
         return boolean;
     }

     void onPostExecute() {
          if(listener!=null) {
               if(boolean) {
                    listener.onInsertProductInDBSuccess():
                } else {
                    listener.onInsertProductInDBFailure();
                }

         }
     }
}

// The rest of the asynctasks follow the same pattern

public class CreateProductFragment extends Fragment implements OnLogInUserToServerListener, OnInsertProductInDBListener, OnUploadProductToServerListener, OnUploadProductImagesToServerListener {

    onCreateView {
        // some stuff 
        buttonSubmit.setOnClickListener(... {

             onClick {
                 new InsertProductInDBAsync(,,,CreateProductFragment.this).execute(); // this is passed as a listener (this fragment is the listener)
             }

        }

    } // End of onCreateView


    @Override
    onInsertProductInDBSuccess(int productId) {
        new LogInUserOnServerAsync(,,,this).execute(); // this is passed as a listener (this fragment is the listener)

    }

    @Override
    onInsertProductInDBFailure() { ... }

    @Override
    onLoginUserOnServerSuccess(User user) {
        new UploadProductOnServerAsync(,,,this).execute():
    }

    @Override
    onLoginUserOnServerFailure() { ... }

    @Override
    onUploadProductOnServerSuccess(int productServerId) {

          for(ProductImage image : product.getImages() {
              image.setProductServerId(productServerId);
              new UpdateProductInDB(product, new OnUpdateProductInDBListener             { 


             @Override
             onUpdateProductInDBSuccess() {
                   new UploadProductImageToServerAsync().execute();
             }

            ... }

              ).execute():
          }

    }

}

现在,我如何将其实现为完全在后台运行并且根本不保留片段的服务?​​

0 个答案:

没有答案