1

I'm trying to create a global actions file in which i can call certain functions globally anywhere within the app. so far i have got it working with functions etc but now what i'm wanting to do is put a standard AsyncTask into my global actions and pass it functions/voids from my Activity so i'd want to pass it a function to run in background and a function to run once finished. does anyone know how do this? and also advise me on running multiple functions on a background thread do i create one AsyncTask and feed in multiple functions or do i create multiple AsyncTasks?

heres an example of what i have managed to do globally so far and how i'm currently implementing my Asynctask. Just to reiterate i'm trying to move the asynctask into a global actions and make it as reusuable as possible

in my Global Actions im creating a function that formulates a URL and sends post variables to that url which then feedsback a JSON response. then in my Activity i have created a function to both call that request and then Log the response

My Global Actions

  public final static JSONObject startAPICallRequest(Context activityContext, String requestReference, String callLocation, Map<String, String> postVarsMap, Map<String, String> getVarsMap){

            long unixTimeStamp = System.currentTimeMillis() / 1000L;

            StringBuilder extraGetVarsString = new StringBuilder();
            if(getVarsMap != null){
                Map<String, String> map = (Map)getVarsMap;
                for (Entry<String, String> entry : map.entrySet()) {
                    extraGetVarsString.append("&" + entry.getKey() + "=" + entry.getValue());
                    extraGetVarsString.toString();
                }
            }

            String appVersion = null;

            try {
                appVersion = activityContext.getPackageManager().getPackageInfo(activityContext.getPackageName(), 0).versionName;

            } catch (NameNotFoundException e) {
                e.printStackTrace();

                appVersion = activityContext.getResources().getString(R.string.appVersion);
            }
            String getVarsString = "?timestamp=" + unixTimeStamp + "&app_version=" + appVersion + extraGetVarsString;
            String apiLocation = activityContext.getResources().getString(R.string.apiLocation);
            String fullAPIURL = apiLocation + callLocation + getVarsString;

            Log.v("globals", "fullAPIURL=" + fullAPIURL);   

            String api_key = activityContext.getResources().getString(R.string.apiKey);
            String api_user = activityContext.getResources().getString(R.string.apiUser);
            String request_token = returnSHAFromString(api_key, fullAPIURL);
            String device_id = returnStringFromPreference(activityContext,"device_id");
            String user_token = returnStringFromPreference(activityContext,"user_token");

            List<NameValuePair> postVarsList = new ArrayList<NameValuePair>();
            postVarsList.add(new BasicNameValuePair("request_token", request_token));
            postVarsList.add(new BasicNameValuePair("api_user", api_user));
            postVarsList.add(new BasicNameValuePair("device_id", device_id));
            postVarsList.add(new BasicNameValuePair("user_token", user_token));

            if(postVarsMap != null){
                Map<String, String> map = (Map)postVarsMap;
                for (Entry<String, String> entry : map.entrySet()) {
                    postVarsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }


            JSONObject responseJSON = null;

            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(fullAPIURL);
                post.setEntity (new UrlEncodedFormEntity(postVarsList));

                HttpResponse response = client.execute(post);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String jsonResponse = reader.readLine();

                Log.v("globals", "postList =" + postVarsList );

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

            return responseJSON;

        }

MY Activity

public void apiCall(){
        responseJSON = GlobalActions.startAPICallRequest(this, "login", "my-network/", null, null);
    }


  public class PostTask extends AsyncTask<Void, String, Boolean> {

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

        }

        @Override
        protected Boolean doInBackground(Void... params) {

            apiCall();
            boolean result = false;
            publishProgress("progress");

            return result;
        }

        protected void onProgressUpdate(String... progress) {
            StringBuilder str = new StringBuilder();
                for (int i = 1; i < progress.length; i++) {
                    str.append(progress[i] + " ");

                }
        }

            @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            checkLoginData();
          }
    }

  public void checkLoginData(){

      Log.v("IntroLoader", "responseJSON = " + responseJSON);
      Intent register = new Intent(getApplicationContext(), LoginForm.class);
      startActivity(register);
  } 
Luke Batley
  • 2,384
  • 10
  • 44
  • 76

3 Answers3

1

Using AsyncTask for calling REST API methods is not really correct approach. Your code has 2 problems:

  • There is no guarantee that your API call will be finished when Activity is closed because process can be killed
  • You have memory leak because PostTask can hold Activity reference even while Activity can be already destroyed

Consider using IntentService for making background requests and e. g. ResultReceiver for handling results in your Activity.

Andrei Mankevich
  • 2,253
  • 16
  • 15
0

It looks like you need a Handler and a Looper. You will be able to post() and postDelayed(). http://developer.android.com/reference/android/os/Handler.html

See also: Is AsyncTask really conceptually flawed or am I just missing something?

Community
  • 1
  • 1
18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
  • hi thans for this was an interesting post. im not entirely sure what you mean abut handlers and loopers and how could i implement that in to my code – Luke Batley Feb 15 '13 at 09:11
0

I'm no Java expert but I don't think you pass functions around in Java. To simplify the matter, what you want to do is call a function in your Activity class when AsyncTask is complete?

JanithaR
  • 1,094
  • 2
  • 11
  • 23