她是我的 android 代码,用于从 twitter 检索用户推文。我在lowerapi版本中成功地做到了这一点。我怎样才能在异步任务中做同样的事情,以避免主线程异常的网络?
public class MainActivity extends ActionBarActivity {
public Bitmap placeholder;
Context mContext;
Twitter mTwitter;
ListView mListView;
static String TWITTER_CONSUMER_KEY = "GHGHGJHghghgjhggM";
static String TWITTER_CONSUMER_SECRET = "jkhKJHjhkjhkHkjhHk38YQXUs";
static String TWITTER_ACCESS_TOKEN = "343434343434-fAZAMIuwAAKlXgby2rXeyvAnhKJHJHJHjhjHJKHjhjhjhhhJ";
static String TWITTER_TOKEN_SECRET = "JBKJkjhJHJJHHFDJBJbhjvghdgsxs";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.ListViewId);
mContext = getApplicationContext();
mTwitter = getTwitter();
ArrayList<Tweet> tweets = showTweetsAbout("IntelAndroid");
ArrayAdapter<Tweet> adapter = new TweetItemAdapter(this, R.layout.listitem, tweets);
mListView.setAdapter(adapter);
}
private Twitter getTwitter() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
cb.setOAuthAccessToken(TWITTER_ACCESS_TOKEN);
cb.setOAuthAccessTokenSecret(TWITTER_TOKEN_SECRET);
cb.setUseSSL(true);
//cb.setJSONStoreEnabled(true);
return new TwitterFactory(cb.build()).getInstance();
}
private ArrayList<Tweet> showTweetsAbout(String queryString) {
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
List<Status> statuses = new ArrayList<Status>();
try {
statuses = mTwitter.search(new Query(queryString)).getTweets();
for (Status s : statuses) {
Tweet tweet = onStatus(s);
tweets.add(tweet);
}
} catch (TwitterException e) {
e.printStackTrace();
}
return tweets;
}