[英]How do put each AsyncTask class in a separate file?
我在主要活動中定義了一些asynstask。 我試圖通過將這些類中的每個類放在單獨的文件中來使代碼更具模塊化。 不幸的是,我不斷收到一些錯誤,例如無法獲得工作意圖。 如何將這段代碼與我的主要活動聯系起來。 順便說一句,如果我將這段代碼原樣(不帶導入)放置在mainActivity中,它就可以正常工作。 謝謝
package com.example.food4thought;
import java.net.URL;
import twitter4j.TwitterException;
import twitter4j.auth.RequestToken;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
// Starts an intent that loads up a web browser and asks the user to log in to twitter
// and get a pin#
public class TwitterLogin extends AsyncTask<URL, Integer, RequestToken> {
protected RequestToken doInBackground(URL... arg0) {
try {
requestToken = twitter.getOAuthRequestToken();
Log.i("Got Request Token", "food4thought");
} catch (TwitterException e) {
Log.i("Failed to get Request Token", "food4thought");
}
//Log.i(requestToken.getAuthorizationURL(), "food4thought");
//requestToken.getAuthorizationURL();
//log_in.setText();
try {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthorizationURL()));
startActivity(browserIntent);
}
catch(NullPointerException e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Unable to log in, No access to the Internet.", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
}
為此,您需要了解AsyncTask具有哪些依賴項。
要觸發意圖,您需要Context
實例。 我還看到一些twitter
變量。
因此,您需要聲明適當的字段並將這些對象傳遞給您的TwitterLogin構造函數。
像這樣:
public class TwitterLogin extends AsyncTask<URL, Integer, RequestToken> {
private Context context;
//other fields here
public TwitterLogin(Context context, ...){ // other variables here
this.context = context;
//other fields assignment
}
}
稍后您可以觸發Intent:
context.startActivity(browserIntent);
重要的是要理解,所有這些方法(例如startActivity)都不是某些“全局函數”,而是某些類實例的方法,您不能僅從AsycTask實例中調用這些方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.