Android中AsyncTask的参数

时间:2015-06-30 11:18:26

标签: android android-asynctask

我试图了解Android中的AsyncTask。我无法理解如何传递参数。在这段代码中:

 protected class AsyncLogin extends AsyncTask<String, JSONObject, Boolean> {
        String userName = null;

        @Override
        protected Boolean doInBackground(String... params)
        {
            RestAPI api = new RestAPI();
            boolean userAuth = false;
            try
            {
                JSONObject jsonObj = api.UserAuthentication(params[0], params[1]);
                JSONParser parser = new JSONParser();
                userAuth = parser.parseUserAuth(jsonObj);
                userName = params[0];

            }
            catch (Exception e)
            {
                Log.d("AsyncLogin", e.getMessage());
            }

            return  userAuth;
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            Toast.makeText(context, "Please wait...", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected  void onPostExecute(Boolean result)
        {
            if(result) {
                Intent i = new Intent(LoginActivity.this, UserDetailsActivity.class);
                i.putExtra("username", userName);
                startActivity(i);
            }
            else
            {
                Toast.makeText(context, "Not valid username/password", Toast.LENGTH_SHORT).show();
            }
        }
    }

我无法理解为什么我们在

中使用<String, JSONObject, Boolean>
protected class AsyncLogin extends AsyncTask<String, JSONObject, Boolean>

String,JSONObject和Boolean是指什么?你能解释一下吗?感谢。

3 个答案:

答案 0 :(得分:1)

Asynch Task实现允许您将一个类型参数作为参数。但是你可以通过向它声明一个参数化构造函数来传递更多的类型参数。 e.g。

class YourAsynchTask extends AsyncTask<ArgumentObject, ProgressObject, ResultObject> {

......

ObjectType1 argument1;
ObjectType2 argument2;
ObjectType3 argument3;

YourAsynchTask(ObjectType1 arg1, ObjectType2 arg2, ObjectType3 arg3) {
argument1 = arg1;
argument2 = arg2;
argument3 = arg3;
    } 


   // rest of the method of your asynch task like doInBackground, etc.
}

您可以像这样调用这种类型的异步任务:

new YourAsynchTask(arg1, arg2, arg3).execute(argumentObjet);

答案 1 :(得分:1)

AsyncTask(Type1,Type2,Type3)使用参数类型:

答案 2 :(得分:0)

            **Calling Api Using AsyncTask In android**




            **MakeServiceCall**


            import android.util.Log;

            import java.io.BufferedReader;
            import java.io.BufferedWriter;
            import java.io.IOException;
            import java.io.InputStreamReader;
            import java.io.OutputStream;
            import java.io.OutputStreamWriter;
            import java.io.UnsupportedEncodingException;
            import java.net.HttpURLConnection;
            import java.net.MalformedURLException;
            import java.net.ProtocolException;
            import java.net.URL;
            import java.net.URLEncoder;
            import java.util.HashMap;
            import java.util.Map;

            import javax.net.ssl.HttpsURLConnection;

            /**
             * Created by archi_info on 2/27/2017.
             */

            public class MakeServiceCall {
                String URl;
                HashMap<String, String> hashMap;
                public static final int GET = 1;
                public static final int POST = 2;
                StringBuilder response;

                public MakeServiceCall()
                {

                }


                public String MakeServiceCall(String URLSTR, int Type) {
                    if (Type == GET)
                    {
                        response = new StringBuilder();
                        try {
                            URL url = new URL(URLSTR);
                            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                            if (httpURLConnection.getResponseCode() == httpURLConnection.HTTP_OK) {
                                BufferedReader input = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()), 8192);
                                String strLine = null;
                                while ((strLine = input.readLine()) != null) {
                                    response.append(strLine);
                                }
                                input.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return response.toString();
                    } else {
                        return "";
                    }
                }


                public String getPostData(String s, HashMap<String, String> PostDataParams) {
                    URL url;
                    String response = "";
                    try {
                        url = new URL(URl);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setReadTimeout(15000);
                        conn.setConnectTimeout(15000);
                        conn.setRequestMethod("POST");
                        conn.setDoInput(true);
                        conn.setDoOutput(true);

                        OutputStream os = conn.getOutputStream();
                        BufferedWriter writer = new BufferedWriter(
                                new OutputStreamWriter(os, "UTF-8"));

                        writer.write(getPostDataString(PostDataParams));
                        writer.flush();
                        writer.close();
                        os.close();
                        int responseCode = conn.getResponseCode();
                        Log.d("StatusCode", "" + responseCode);
                        if (responseCode == HttpsURLConnection.HTTP_OK) {
                            String line;
                            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                            while ((line = br.readLine()) != null) {
                                response += line;
                            }
                        } else {
                            response = "";

                        }
                        return response;
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (ProtocolException e) {
                        e.printStackTrace();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return response;
                }

                private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
                    StringBuilder result=new StringBuilder();
                    boolean first=true;
                    for (Map.Entry<String,String>entry:params.entrySet())
                    {
                        if(first)
                            first=false;
                        else
                            result.append("&");

                        result.append(URLEncoder.encode(entry.getKey(),"UTF-8"));
                        result.append("=");
                        result.append(URLEncoder.encode(entry.getValue(),"UTF-8"));
                    }
                    Log.d("msg","makeservice"+result.toString());
                    return result.toString();
                }


            }



        **ConnectionDetector**

        import android.app.Dialog;
        import android.content.Context;
        import android.content.Intent;
        import android.net.ConnectivityManager;
        import android.net.NetworkInfo;
        import android.provider.Settings;
        import android.view.View;
        import android.view.Window;
        import android.widget.Button;



        public class ConnectionDetector
        {
            private Context context;
            public ConnectionDetector(Context context)
            {
                this.context = context;
            }
            public boolean isConnectingToInternet()
            {
                ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (connectivity != null) {
                    NetworkInfo[] info = connectivity.getAllNetworkInfo();
                    if (info != null)
                    {
                        for (int i = 0; i < info.length; i++)

                            if (info[i].getState() == NetworkInfo.State.CONNECTED)
                            {
                                return true;
                            }
                    }
                }
            return false;
            }

            public boolean connectionDetected()
            {
                if (isConnectingToInternet()) {
                    return true;
                } else {
                    final Dialog dialog = new Dialog(context);
                    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    dialog.setContentView(R.layout.connection_checker);
                    Button ok = (Button) dialog.findViewById(R.id.dialog_ok);
                    Button cancel = (Button) dialog.findViewById(R.id.dialog_cancel);
                    ok.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            connectionDetected();
                        }
                    });
                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view)
                        {
                            dialog.dismiss();
                            context.startActivity(new Intent(Settings.ACTION_SETTINGS));
                        }
                    });
                    return false;
                }
            }
        }



    **Utils** 


    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.pm.PackageManager;
    import android.graphics.Bitmap;
    import android.location.Location;
    import android.net.ConnectivityManager;
    import android.net.Network;
    import android.net.NetworkInfo;
    import android.os.Build;
    import android.os.StrictMode;
    import android.preference.PreferenceManager;
    import android.util.Base64;
    import android.util.Log;

    import com.google.gson.Gson;

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.UnsupportedEncodingException;
    import java.lang.reflect.Type;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;

    import javax.net.ssl.HttpsURLConnection;


    public class Utils {
        static Context context;
        SharedPreferences sp;
        Location getLocation;

        public Utils(Context context) {
            this.context = context;
            sp = context.getSharedPreferences(Constant.Prefrence, Context.MODE_PRIVATE);
        }

        public String getReadSharedPrefrenceIsFirstTime(Context activity, String userid) {
            String defValue = "";
            String resposne = sp.getString(Constant.ISFIRSTTIME, defValue);
            return resposne;
        }

        public static String convertToGson(Object object) {
            Gson gson = new Gson();
            String loginResult = gson.toJson(object);
            return loginResult;
        }

        public static <T> T GsonToObject(String strObj, Type classObject) {
            Gson gson = new Gson();
            return gson.fromJson(strObj, classObject);
        }


        public void clearSharedPreferenceData() {
            sp.edit().clear().commit();
        }

        public String getResponseofPost(String URL, HashMap<String, String> postDataParams) {
            URL url;
            String response = "";
            try {
                url = new URL(URL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));

                writer.write(getPostDataString(postDataParams));
                writer.flush();
                writer.close();
                os.close();
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        response += line;
                    }
                } else {
                    response = "";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        public static String getResponseofGet(String URL) {
            URL url;
            String response = "";
            try {

                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
                url = new URL(URL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.setDoOutput(true);

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));

                writer.flush();
                writer.close();
                os.close();
                int responseCode = conn.getResponseCode();
                Log.d("URL - ResponseCode", URL + " - " + responseCode);
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        response += line;
                    }
                } else {
                    response = "";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        private String getPostDataString(HashMap<String, String> params) throws
                UnsupportedEncodingException {
            StringBuilder result = new StringBuilder();
            boolean first = true;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (first)
                    first = false;
                else
                    result.append("&");

                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            return result.toString();
        }

        public String MakeServiceCall(String URLSTR) {
            StringBuilder response = null;
            try {
                response = new StringBuilder();
                URL url = new URL(URLSTR);
                HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
                if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()), 8192);
                    String strLine = null;
                    while ((strLine = input.readLine()) != null) {
                        response.append(strLine);
                    }
                    input.close();
                }
            } catch (Exception e) {
            }
            return response.toString();
        }

        private boolean appInstalledOrNot(String packageName) {
            PackageManager pm = context.getPackageManager();
            boolean app_installed;
            try {
                pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
                app_installed = true;
            } catch (PackageManager.NameNotFoundException e) {
                app_installed = false;
            }
            return app_installed;
        }

        public static boolean isConnectingToInternet(Context context)
        {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Network[] networks = connectivityManager.getAllNetworks();
                NetworkInfo networkInfo;
                for (Network mNetwork : networks)
                {
                    networkInfo = connectivityManager.getNetworkInfo(mNetwork);
                    if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                        return true;
                    }
                }
            } else {
                if (connectivityManager != null)
                {
                    NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
                    if (info != null) {
                        for (NetworkInfo anInfo : info) {
                            if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }

        public static void WriteSharePrefrence(Context context, String key, String value)
        {
            final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            final SharedPreferences.Editor editor = preferences.edit();
            editor.putString(key, value);
            editor.commit();
        }

        public static String ReadSharePrefrence(Context context, String key)
        {
            String data;
            final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            final SharedPreferences.Editor editor = preferences.edit();
            data = preferences.getString(key, "");
            editor.commit();
            return data;
        }




        public static void Clear(Context context, String key)
        {
            String data;
            final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            final SharedPreferences.Editor editor = preferences.edit().clear();
            editor.commit();
        }

        public static void ClearaSharePrefrence(Context context) {
            String data;
            final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            final SharedPreferences.Editor editor = preferences.edit().clear();
            editor.commit();
        }

        public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality) {
            ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
            image.compress(compressFormat, quality, byteArrayOS);
            return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);
        }

        public static String getLeaveStatus(String status) {
            String result = "";
            switch (status) {
                case "0":
                    result = "Pending";
                    break;
                case "1":
                    result = "Aproved";
                    break;
                case "2":
                    result = "Cancel";
                    break;
            }
            return result;
        }


        public String parseDateToddMMyyyy(String time)
        {
            String inputPattern = "yyyy-MM-dd HH:mm:ss";
            String outputPattern = "yyyy-MM-dd";
            SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
            SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
            Date date = null;
            String str = null;
            try {
                date = inputFormat.parse(time);
                str = outputFormat.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return str;
        }
    }


**MainActivity**

private ListView list;
    public EmployeeListSetget employeeListSetget;
    public ArrayList<EmployeeListSetget> arrayList;
    public Context context = this;
    public Utils utils;
    private EmployeeListAdapter adapter;
    public ImageView backbtn;
    public Button btn_showchart;
    public ACProgressFlower dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_employee_list);
        utils = new Utils(EmployeeList.this);
        backbtn = (ImageView) findViewById(R.id.employeelist_backbutton);
        backbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        btn_showchart = (Button) findViewById(R.id.admin_employee_list_btnshowchart);

        btn_showchart.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                Intent in = new Intent(EmployeeList.this, AddEmployeeActivity.class);
                startActivity(in);
            }
        });

        if (utils.isConnectingToInternet(EmployeeList.this)) {
            new EmployeegetList().execute();
        } else {
            Toast.makeText(EmployeeList.this, R.string.error_nointernet, Toast.LENGTH_SHORT).show();
        }
    }

    private class EmployeegetList extends AsyncTask<String, String, String> {

        ProgressDialog pd;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            arrayList = new ArrayList<>();
            pd = new ProgressDialog(EmployeeList.this);
            pd.setMessage("Loading...");
            pd.setCancelable(false);
            pd.show();
        }

        @Override
        protected String doInBackground(String... params) {
            return utils.getResponseofGet(Constant.BASE_URL + "get_employee_list.php");
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pd.dismiss();
            try {
                JSONObject jsonObject = new JSONObject(s);
                if (jsonObject.getString("status").equalsIgnoreCase("true")) {
                    pd.dismiss();
                    arrayList = new ArrayList<>();
                    JSONArray array = jsonObject.getJSONArray("employee_detail");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jsonObj = array.getJSONObject(i);
                        employeeListSetget = new EmployeeListSetget();
                        employeeListSetget.setEmp_listId(jsonObj.getString("emp_id"));
                        employeeListSetget.setEmp_listName(jsonObj.getString("emp_name"));
                        employeeListSetget.setEmp_listImage(jsonObj.getString("emp_image"));
                        employeeListSetget.setEmp_listDatetime("Since " + parseDateToddMMyyyy(jsonObj.getString("emp_join_date")));
                        arrayList.add(employeeListSetget);
                    }
                } else {
                    pd.dismiss();
                    Toast.makeText(context, R.string.somethingwentwrong, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (arrayList != null) {
                list = (ListView) findViewById(R.id.employee_getlistview);
                adapter = new EmployeeListAdapter(context, arrayList);
                list.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            } else {
                Toast.makeText(context, R.string.somethingwentwrong, Toast.LENGTH_SHORT).show();
            }
        }
    }

    public String parseDateToddMMyyyy(String time) {
        String inputPattern = "yyyy-MM-dd HH:mm:ss";
        String outputPattern = "dd-MMM-yyyy";
        SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
        SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
        Date date = null;
        String str = null;
        try {
            date = inputFormat.parse(time);
            str = outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return str;
    }
}