从其他片段调用静态异步任务

时间:2014-06-18 18:27:27

标签: android static android-asynctask

我试图从片段中调用其他活动中的Async任务。我试着以各种方式打电话,但没有一个有效。我只想知道什么是调用静态AsyncTask的最佳方法。这是我的异步任务:

static class MyAsync extends AsyncTask<Void, Void, Void> {
    Context context;
    String username, password;
    private MyAsync(Context context, String username, String password) {
        this.context = context;
        this.username = username;
        this.password = password;
    }
    ProgressDialog dialog;
    private String response;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = ProgressDialog.show(context, "Connecting to Server","Getting Credentials"
                , true);
    }

    @Override
    protected Void doInBackground(Void... arg0) {       
        try {               
                ContentDownload download = new ContentDownload();
                response = download.loginApi(agentId, password);
                 if(response.contains("Success")){
                     if(SettingHelper.getFirstCall(context)){
                         ContentDownload.CallApi(context);
                         SettingHelper.setFirstCall(context, false);
                     }
                     if(SettingHelper.getFirstLaunch(context)){
                         ContentDownload load = new ContentDownload();
                         load.callItemApi(context);
                         load.callActionApi(context);
                         SettingHelper.setFirstLaunch(context, false);
                     }
            }
        } catch (Exception e) {
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if(response.contains("Success")){
         context.startActivity(new Intent(context, AllActivity.class));
        }else{
            Toast.makeText(context, "Got back", Toast.LENGTH_SHORT).show();
        }
    dialog.dismiss();
}}  

我试着这样称呼它:

      LoginActivity.new MyAsync(getActivity).execute();

但是给出错误

1 个答案:

答案 0 :(得分:0)

您希望使用Fragment中的此类,公开提供公开功能,以及公共构造函数,然后您可以调用它:

new LoginActivity.MyAsync(getActivity())