我正在尝试创建一个全局动作文件,我可以在应用程序中的任何位置全局调用某些功能。到目前为止,我已经使用了函数等,但现在我想要做的是将标准的AsyncTask放入我的全局操作并从我的Activity中传递函数/空洞,所以我想传递一个函数来运行背景和一个完成后运行的功能。有谁知道这是怎么回事?并建议我在后台线程上运行多个函数我创建一个AsyncTask并提供多个函数,还是创建多个AsyncTasks?
这是我迄今为止在全球范围内设法做的一个例子以及我目前如何实现我的Asynctask。只是重申我正试图将asynctask转移到全局行动中,并使其尽可能重复使用
在我的全局操作中创建一个函数,该函数可以制定URL并将post变量发送到该url,然后反馈JSON响应。然后在我的Activity中我创建了一个函数来调用该请求然后记录响应
我的全球行动
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;
}
我的活动
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);
}
答案 0 :(得分:1)
使用AsyncTask
调用REST API方法并不是真正正确的方法。您的代码有两个问题:
PostTask
也可以保存活动参考考虑使用IntentService来提出后台请求和e。 G。 ResultReceiver用于处理Activity
。
答案 1 :(得分:0)
看起来你需要一个Handler和一个Looper。您将能够发布()和postDelayed()。 http://developer.android.com/reference/android/os/Handler.html
另见: Is AsyncTask really conceptually flawed or am I just missing something?
答案 2 :(得分:0)
我不是Java专家,但我不认为你在Java中传递函数。为简化此事,您想要做的是在AsyncTask完成时调用Activity类中的函数?