在android中使用Async任务调用Web服务?

Ran*_*ngh 1 android web-services android-asynctask

我有一个单独的Web服务类,其中我只传递响应方法,url和数组列表,这些数据是发出请求和获取响应所必需的.我在这样的登录活动中调用此Web服务

JifWebService webServices = new JifWebService();
                webServices.Execute(RequestMethod.POST,
                        Jifconstant.LOGIN_URL, null, logindata);
                loginResponse = webServices.getResponse();
                loginResponseCode = webServices.getResponseCode();
Run Code Online (Sandbox Code Playgroud)

在此登录数据中是包含一些数据的数组列表.现在我想使用异步任务在后台调用此Web服务.但我只是没弄错.我的Web服务逻辑是用完全不同的java文件编写的,它的工作正常,但我想在异步任务中调用我的Web服务方法.enter code here

Hir*_*tel 6

您可以尝试以下Async Task代码,并在doInBackground中调用Web服务:

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;

public class AsyncExample extends Activity{


private String url="http://www.google.co.in";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     new AsyncCaller().execute();
}


private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
    ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("Loading...");
        pdLoading.show();
    }
    @Override
    protected Void doInBackground(Void... params) {

        //this method will be running on a background thread so don't update UI from here
        //do your long-running http tasks here, you don't want to pass argument and u can access the parent class' variable url over here


        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        //this method will be running on UI thread

        pdLoading.dismiss();
    }

    }
}
Run Code Online (Sandbox Code Playgroud)

完成