传递函数为一个全球性的AsyncTask的Andr​​oid [英] Passing functions into a global AsyncTask Android

查看:113
本文介绍了传递函数为一个全球性的AsyncTask的Andr​​oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个全球行动文件,在其中我可以在应用程序内全球任何地方调用某些功能。到目前为止,我已经得到了它的功能等,但现在什么我想要做的就是把一个标准的AsyncTask到我的全球行动,并将其传递函数/从我的活动空隙,所以我会想传递一个函数来运行工作背景和函数运行一次吃完。没有人知道如何做到这一点?同时也提醒我在后台线程运行多个功能做我创建多个功能之一的AsyncTask和饲料或做我创建多个AsyncTasks?

继承人什么,我已经成功地做​​到全球迄今为止一个例子,如何我目前正在实施我的AsyncTask。只是重申我想要的AsyncTask的移动到一个全球性的行动,并使其作为reusuable尽可能

在我的全球即时通讯的行动创造一个制定和URL发送POST变量到该网址,然后feedsback的JSON响应的功能。然后在我的活动我已经创建了既函数调用请求,然后登录响应

我的全局操作

 公共最后静态的JSONObject startAPICallRequest(上下文activityContext,字符串requestReference,字符串callLocation,地图<字符串,字符串> postVarsMap,地图<字符串,字符串> getVarsMap){            长unixTimeStamp = System.currentTimeMillis的()/ 1000L;            StringBuilder的extraGetVarsString =新的StringBuilder();
            如果(getVarsMap!= NULL){
                地图<字符串,字符串>地图=(图)getVarsMap;
                对于(进入<字符串,字符串>项:map.entrySet()){
                    extraGetVarsString.append(与&+ entry.getKey()+=+ entry.getValue());
                    extraGetVarsString.toString();
                }
            }            字符串appVersion = NULL;            尝试{
                appVersion = activityContext.getPackageManager()getPackageInfo(activityContext.getPackageName(),0).versionName。            }赶上(ē的NameNotFoundException){
                e.printStackTrace();                appVersion = activityContext.getResources()的getString(R.string.appVersion)。
            }
            字符串getVarsString = + unixTimeStamp +时间戳=?,&放大器; APP_VERSION =+ appVersion + extraGetVarsString;
            字符串apiLocation = activityContext.getResources()的getString(R.string.apiLocation)。
            字符串fullAPIURL = apiLocation + callLocation + getVarsString;            Log.v(全局,fullAPIURL =+ fullAPIURL);            字符串API_KEY = activityContext.getResources()的getString(R.string.apiKey)。
            。字符串api_user = activityContext.getResources()的getString(R.string.apiUser);
            字符串request_token = returnSHAFromString(API_KEY,fullAPIURL);
            字符串DEVICE_ID = returnStringFrom preference(activityContextDEVICE_ID);
            字符串user_token = returnStringFrom preference(activityContextuser_token);            清单<&的NameValuePair GT; postVarsList =新的ArrayList<&的NameValuePair GT;();
            postVarsList.add(新BasicNameValuePair(request_token,request_token));
            postVarsList.add(新BasicNameValuePair(api_user,api_user));
            postVarsList.add(新BasicNameValuePair(DEVICE_ID,DEVICE_ID));
            postVarsList.add(新BasicNameValuePair(user_token,user_token));            如果(postVarsMap!= NULL){
                地图<字符串,字符串>地图=(图)postVarsMap;
                对于(进入<字符串,字符串>项:map.entrySet()){
                    postVarsList.add(新BasicNameValuePair(entry.getKey(),entry.getValue()));
                }
            }
            JSONObject的responseJSON = NULL;            尝试{
                HttpClient的客户端=新DefaultHttpClient();
                HttpPost后=新HttpPost(fullAPIURL);
                post.setEntity(新UrlEn codedFormEntity(postVarsList));                HTT presponse响应= client.execute(岗位);
                的BufferedReader读者=新的BufferedReader(新的InputStreamReader(response.getEntity()的getContent(),UTF-8)。);
                串jsonResponse = reader.readLine();                Log.v(全局,postList =+ postVarsList);            }赶上(ClientProtocolException E){
                // TODO自动生成catch块
                e.printStackTrace();
            }赶上(IOException异常五){
                // TODO自动生成catch块
                e.printStackTrace();
            }            返回responseJSON;        }

我的活动

 公共无效apiCall(){
        responseJSON = GlobalActions.startAPICallRequest(这一点,登录,我的网络/,NULL,NULL);
    }
  公共类PostTask扩展的AsyncTask<无效,字符串,布尔值> {        在preExecute保护无效(){
            super.on preExecute();        }        @覆盖
        保护布尔doInBackground(虚空...... PARAMS){            apiCall();
            布尔结果= FALSE;
            publishProgress(进步);            返回结果;
        }        保护无效onProgressUpdate(字符串...进度){
            StringBuilder的海峡=新的StringBuilder();
                的for(int i = 1; I< progress.length;我++){
                    str.append(进度[I] +);                }
        }            @覆盖
        保护无效onPostExecute(布尔结果){
            super.onPostExecute(结果);
            checkLoginData();
          }
    }  公共无效checkLoginData(){      Log.v(IntroLoader,responseJSON =+ responseJSON);
      意向登记=新意图(getApplicationContext(),LoginForm.class);
      startActivity(注册);
  }


解决方案

使用的AsyncTask 调用REST API方法是不是真的正确的做法。您code有2个问题:


  • 有没有保证您的API调用时将活动被关闭,因为过程可以杀死完成

  • 您有内存泄漏,因为 PostTask 可容纳活动参考即使活动已经可以摧毁

考虑使用 IntentService 制作背景的要求和电子商务。 G。 ResultReceiver 在你的活动处理结果

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);
  } 

解决方案

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.

这篇关于传递函数为一个全球性的AsyncTask的Andr​​oid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆