如何从多个活动中调用单个服务?

时间:2018-05-23 10:35:51

标签: android service httpurlconnection

我是android的新用户,曾在ReactJS工作过。在反应中,很容易在单独的文件中创建后端服务,并通过简单的ajax调用来访问它 要在android中调用该服务,我有用户HttpURLConnection

它工作但是,有没有办法在android项目的单独文件夹中定义HttpURLConnection服务调用,并从android中的any of the activity调用它&什么时候需要return response到活动类。

1 个答案:

答案 0 :(得分:0)

这是用于所有类型的服务调用的服务类,如Get,Post等,这是使用它的公共基类,我们可以为特定服务创建其他子类,因此我们可以在任何地方调用它

public class ServiceCall {

//Error Codes
private final int OK = 200;
private final int NETWORK_ERROR = 9001;
private final int SERVER_ERROR = 9002;
private final int AUTH_FAILURE_ERROR = 9003;
private final int PARSE_ERROR = 9004;
private final int NO_CONNECTION_ERROR = 9005;
private final int TIME_OUT_ERROR = 9006;
private final int UNKNOWN_ERROR = 9007;

private String LOG_TAG = ServiceCall.class.getName();

private String url;
private HashMap<String, String> hashMap;
private IRestApiListener iRestApiListener;
private int requestMethod;
private HashMap<String, File> fileparts;
private boolean show_no_intenet_message = true;
private Context context;

public ServiceCall(Context context, String url, HashMap<String, String> hashMap, IRestApiListener iRestApiListener) {
    this.context = context;
    this.url = url;
    this.hashMap = hashMap;
    this.requestMethod = Integer.parseInt(RequestMethod.POST.toString());
    this.iRestApiListener = iRestApiListener;

    //This is an optionl parameter for this project only Fresh Fills
    setExtraParameterInHashMap(this.hashMap);

    //Check network connection
    if (isInernetConnectionIsAvailable()) {
        iRestApiListener.onNetowkisOn();
        RestApiCall();
    } else {
        iRestApiListener.onNoNetwork();
        if (show_no_intenet_message) {
            showNoInternetMessage();
        }
    }

}

public ServiceCall(Context context, String url, HashMap<String, String> hashMap, RequestMethod requestMethod, IRestApiListener iRestApiListener) {
    this.context = context;
    this.url = url;
    this.hashMap = hashMap;
    this.iRestApiListener = iRestApiListener;
    this.requestMethod = Integer.parseInt(requestMethod.toString());

    //This is an optionl parameter for this project only Fresh Fills
    setExtraParameterInHashMap(this.hashMap);

    //Check network connection
    if (isInernetConnectionIsAvailable()) {
        iRestApiListener.onNetowkisOn();
        RestApiCall();
    } else {
        iRestApiListener.onNoNetwork();
        if (show_no_intenet_message) {
            showNoInternetMessage();
        }
    }

}

public ServiceCall(Context context, String url, HashMap<String, String> hashMap, HashMap<String, File> fileparts, RequestMethod requestMethod, IRestApiListener iRestApiListener) {
    this.context = context;
    this.url = url;
    this.hashMap = hashMap;
    this.fileparts = fileparts;
    this.iRestApiListener = iRestApiListener;
    this.requestMethod = Integer.parseInt(requestMethod.toString());

    //This is an optionl parameter for this project only Fresh Fills
    setExtraParameterInHashMap(this.hashMap);

    //Check network connection
    if (isInernetConnectionIsAvailable()) {
        iRestApiListener.onNetowkisOn();
        UploadImage();
    } else {
        iRestApiListener.onNoNetwork();
        if (show_no_intenet_message) {
            showNoInternetMessage();
        }
    }


}

//This is an optionl parameter for this project only Fresh Fills
private void setExtraParameterInHashMap(HashMap<String, String> map) {
    map.put("apiKey", "Yck8g9]gxo1uXHx[72h?EX:j!VL7l9");
    map.put("langId", "1");
    map.put("version", "1");
}

/**
 * Get ,Post Method call
 */
private void RestApiCall() {

    StringRequest commonRequest = new StringRequest(requestMethod, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i(LOG_TAG, "URL " + url + "\n Response : " + response);
            if (iRestApiListener != null) {
                setparsing(response);
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // Handle your error types accordingly.For Timeout & No
            // connection error, you can show 'retry' button.
            // For AuthFailure, you can re login with user
            // credentials.
            // For ClientError, 400 & 401, Errors happening on
            // client side when sending api request.
            // In this case you can check how client is forming the
            // api and debug accordingly.
            // For ServerError 5xx, you can do retry or handle
            // accordingly.
            int errorCode;
            if (error instanceof NetworkError) {
                errorCode = NETWORK_ERROR;
                Log.i(LOG_TAG, "NetworkError" + error);
            } else if (error instanceof ServerError) {
                errorCode = SERVER_ERROR;
                Log.i(LOG_TAG, "ServerError" + error);
            } else if (error instanceof AuthFailureError) {
                errorCode = AUTH_FAILURE_ERROR;
                Log.i(LOG_TAG, "AuthFailureError" + error);
            } else if (error instanceof ParseError) {
                errorCode = PARSE_ERROR;
                Log.i(LOG_TAG, "ParseError" + error);
            } else if (error instanceof NoConnectionError) {
                errorCode = NO_CONNECTION_ERROR;
                Log.i(LOG_TAG, "NoConnectionError" + error);
            } else if (error instanceof TimeoutError) {
                errorCode = TIME_OUT_ERROR;
                Log.i(LOG_TAG, "TimeoutError" + error);
            } else {
                errorCode = UNKNOWN_ERROR;
                Log.i(LOG_TAG, "TimeoutError" + error);
            }

            //Log.i(LOG_TAG,"StatusCode" + error.networkResponse.statusCode);
            if (iRestApiListener != null) {
                iRestApiListener.onCallFinish();
                iRestApiListener.onError(new JSONArray());
            }
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Authorization", "Bearer " + AppClass.preferences.getValueFromPreferance(Preferences.TOKEN));
            Log.d("Logger", "Authorization: " + AppClass.preferences.getValueFromPreferance(Preferences.TOKEN));
            return params;
        }


        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            return hashMap;
        }
    };

    commonRequest.setRetryPolicy(new DefaultRetryPolicy(60000, 1, 1));
    AppClass.mVolleyInstance.addToRequestQueue(commonRequest);
}

/**
 * Upload image
 */
private void UploadImage() {

    RestApiMultiPartRequests<String> restApiMultiPartRequest =
            new RestApiMultiPartRequests<String>(url, hashMap, fileparts, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i(LOG_TAG, "URL " + url + "\n Response : " + response);
                    if (iRestApiListener != null) {
                        setparsing(response);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // Handle your error types accordingly.For Timeout & No
                    // connection error, you can show 'retry' button.
                    // For AuthFailure, you can re login with user
                    // credentials.
                    // For ClientError, 400 & 401, Errors happening on
                    // client side when sending api request.
                    // In this case you can check how client is forming the
                    // api and debug accordingly.
                    // For ServerError 5xx, you can do retry or handle
                    // accordingly.
                    int errorCode;
                    if (error instanceof NetworkError) {
                        errorCode = NETWORK_ERROR;
                        Log.i(LOG_TAG, "NetworkError" + error);
                    } else if (error instanceof ServerError) {
                        errorCode = SERVER_ERROR;
                        Log.i(LOG_TAG, "ServerError" + error);
                    } else if (error instanceof AuthFailureError) {
                        errorCode = AUTH_FAILURE_ERROR;
                        Log.i(LOG_TAG, "AuthFailureError" + error);
                    } else if (error instanceof ParseError) {
                        errorCode = PARSE_ERROR;
                        Log.i(LOG_TAG, "ParseError" + error);
                    } else if (error instanceof NoConnectionError) {
                        errorCode = NO_CONNECTION_ERROR;
                        Log.i(LOG_TAG, "NoConnectionError" + error);
                    } else if (error instanceof TimeoutError) {
                        errorCode = TIME_OUT_ERROR;
                        Log.i(LOG_TAG, "TimeoutError" + error);
                    } else {
                        errorCode = UNKNOWN_ERROR;
                        Log.i(LOG_TAG, "TimeoutError" + error);
                    }

                    //Log.i(LOG_TAG,"StatusCode" + error.networkResponse.statusCode);
                    if (iRestApiListener != null) {
                        iRestApiListener.onCallFinish();
                        iRestApiListener.onError(new JSONArray());
                    }
                }
            }) {

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    if (StringUtils.isNotEmpty(AppClass.preferences.getValueFromPreferance(Preferences.TOKEN))) {
                        params.put("Authorization", "Bearer " + AppClass.preferences.getValueFromPreferance(Preferences.TOKEN));
                    }

                    return params;
                }

                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    return params;
                }
            };

    restApiMultiPartRequest.setRetryPolicy(new DefaultRetryPolicy(0, 1, 2));//10000
    AppClass.mVolleyInstance.addToRequestQueue(restApiMultiPartRequest);
}

/**
 * Parse the response
 *
 * @param response
 */
private void setparsing(String response) {
    if (StringUtils.isNotEmpty(response)) {
        try {
            JSONArray jsonArray = new JSONArray();

            JSONObject jsonObject = new JSONObject(response);
            jsonArray.put(jsonObject);

            if(jsonArray.getJSONObject(0).has("status")){
                String status = String.valueOf(jsonArray.getJSONObject(0).getInt("status"));
                if (status.equals("1")) {
                    iRestApiListener.onCallFinish();
                    iRestApiListener.onResponseTrue(jsonArray);
                } else {
                    iRestApiListener.onCallFinish();
                    iRestApiListener.onResponseFalse(jsonArray);

                }
            }else {
                iRestApiListener.onCallFinish();
                iRestApiListener.onResponseTrue(jsonArray);
            }


        } catch (JSONException e) {
            e.printStackTrace();
            iRestApiListener.onError(new JSONArray());
        }

    }
}

/**
 * Created by Jay
 * Enum return type of service call
 */
public enum RequestMethod {
    DEPRECATED_GET_OR_POST {
        @Override
        public String toString() {
            return Request.Method.DEPRECATED_GET_OR_POST + "";
        }
    },
    GET {
        @Override
        public String toString() {
            return Request.Method.GET + "";
        }
    },
    POST {
        @Override
        public String toString() {
            return Request.Method.POST + "";
        }
    },
    PUT {
        @Override
        public String toString() {
            return Request.Method.PUT + "";
        }
    },
    DELETE {
        @Override
        public String toString() {
            return Request.Method.DELETE + "";
        }
    },
    HEAD {
        @Override
        public String toString() {
            return Request.Method.HEAD + "";
        }
    },
    OPTIONS {
        @Override
        public String toString() {
            return Request.Method.OPTIONS + "";
        }
    },
    TRACE {
        @Override
        public String toString() {
            return Request.Method.TRACE + "";
        }
    },
    PATCH {
        @Override
        public String toString() {
            return Request.Method.PATCH + "";
        }
    },
}

/**
 * Mutipart Request Calss
 *
 * @param <T>
 */
private class RestApiMultiPartRequests<T> extends Request<T> {

    private final Map<String, String> mStringParts;
    private final Map<String, File> mFileParts;
    private MultipartEntityBuilder mBuilder;
    private final Response.Listener<T> mListener;

    public RestApiMultiPartRequests(String url,
                                    Map<String, String> stringParts,
                                    Map<String, File> fileParts,
                                    Response.Listener<T> listener,
                                    Response.ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        mListener = listener;
        mStringParts = stringParts;
        mFileParts = fileParts;
        buildMultipartEntity();
    }

    private void buildMultipartEntity() {
        if (mBuilder != null) {
            mBuilder = null;
        }
        mBuilder = MultipartEntityBuilder.create();
        mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        mBuilder.setBoundary("_____" + Long.toString(System.currentTimeMillis()) + "_____");
        mBuilder.setCharset(Consts.UTF_8);
        if (mStringParts != null) {
            for (Map.Entry<String, String> entry : mStringParts.entrySet()) {
                mBuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", Charset.forName("UTF-8")));
            }
        }

        Log.e("Size", "Size: " + mFileParts.size());
        for (Map.Entry<String, File> entry : mFileParts.entrySet()) {
            ContentType imageContentType = ContentType.create("image/*");//MULTIPART_FORM_DATA;
            Log.d("", "Key " + entry.getKey());
            Log.d("", "Value " + entry.getValue());
            Log.d("", "Name " + entry.getValue().getName());
            //"userfile"
            mBuilder.addBinaryBody(entry.getKey(), entry.getValue(), imageContentType, entry.getValue().getName());
        }

    }

    @Override
    public String getBodyContentType() {
        return mBuilder.build().getContentType().getValue();
    }

    @Override
    public byte[] getBody() {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            mBuilder.build().writeTo(bos);
        } catch (IOException e) {
            e.printStackTrace();
            iRestApiListener.onError(new JSONArray());
        }

        return bos.toByteArray();
    }


    public HttpEntity getEntity() {
        return mBuilder.build();
    }


    @SuppressWarnings("unchecked")
    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return (Response<T>) Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(T response) {
        mListener.onResponse(response);

    }


}

/**
 * Check network availibility
 *
 * @return
 */
private boolean isInernetConnectionIsAvailable() {
    boolean flag = false;
    if (AppClass.networkConnectivity.isNetworkAvailable()) {
        flag = true;
    } else {
        flag = false;
    }
    return flag;
}

/**
 * Show no internet message
 */
private void showNoInternetMessage() {
    AppClass.snackBarView.snackBarShow(context, context.getString(R.string.nonetwork));
}

/**
 * true , false show internet message or not
 *
 * @param flag
 * @return
 */
public ServiceCall setAllowDisAllowInternetMessage(boolean flag) {
    this.show_no_intenet_message = false;
    return this;
}


public interface IRestApiListener {

    public void onResponseTrue(JSONArray jsonArray) throws JSONException;

    public void onResponseFalse(JSONArray jsonArray) throws JSONException;

    public void onError(JSONArray jsonArray);

    public void onNoNetwork();

    public void onNetowkisOn();

    public void onCallFinish();
}

}

我已经创建了这个类来调用api中的登录

public class LoginApiCall {
private ProgressDialog progressDialog;
private BaseActivity activity;
private String
        email = "",
        password = "";
private OnServiceDoneListener listener;

public LoginApiCall(BaseActivity activity, String email, String password, OnServiceDoneListener listener) {
    this.activity = activity;
    this.email = email;
    this.password = password;
    this.listener = listener;

    serviceCall();
}

private void serviceCall() {
    HashMap<String, String> hashMap = new HashMap<>();
    hashMap.put("email", email);
    hashMap.put("password", password);
    new ServiceCall(activity, Api.login, hashMap, new ServiceCall.IRestApiListener() {
        @Override
        public void onResponseTrue(JSONArray jsonArray) throws JSONException {
            Gson gson = new Gson();
            LoginModel loginModel = gson.fromJson(jsonArray.getJSONObject(0).toString(), LoginModel.class);
            listener.onSuccess(true, loginModel);
        }

        @Override
        public void onResponseFalse(JSONArray jsonArray) throws JSONException {
            activity.setLogOut(activity, jsonArray);
            listener.onServiceFail(false,jsonArray.getJSONObject(0).getInt("status"), jsonArray.getJSONObject(0).getString("message"));

        }

        @Override
        public void onError(JSONArray jsonArray)  {
            try {
                listener.onServiceFail(false,jsonArray.getJSONObject(0).getInt("status"), jsonArray.getJSONObject(0).getString("message"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onNoNetwork() {
        }

        @Override
        public void onNetowkisOn() {
            showOrDissMissProgressDialog(1);
        }

        @Override
        public void onCallFinish() {
            showOrDissMissProgressDialog(0);
        }
    });
}

/**
 * <p> Created by Jay <p/>
 * Show and dismiss progress dilaog
 * and alos initialied within the method
 *
 * @param flag eg. 1 show 0 hide
 */
private void showOrDissMissProgressDialog(int flag) {
    switch (flag) {
        case 0:
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
            break;
        case 1:
            progressDialog = new ProgressDialog(activity);
            progressDialog.setTitle(activity.getString(R.string.app_name));
            progressDialog.setMessage(activity.getString(R.string.please_wait));
            progressDialog.show();
            break;
    }

}

public interface OnServiceDoneListener {
public void onSuccess(boolean status, LoginModel loginModel);

public void onServiceFail(boolean status, int satatus,String response_message);

} }

现在使用此代码从任何地方和任何活动中调用此api

 new LoginApiCall(
                    LoginActivity.this,
                    JsSystemHelper.getStringFromView(edLoginEmail),
                    JsSystemHelper.getStringFromView(edLoginPassword),
                    new LoginApiCall.OnServiceDoneListener() {
                        @Override
                        public void onSuccess(boolean status, LoginModel loginModel) {
                           //RESPONSE TRUE

                        }

                        @Override
                        public void onServiceFail(boolean status, int satatus, final String response_message) {
                          //RESPONSE FALSE

                            }

                        }

                    }
            );
        }