我在我的服務中使用AsyncTask,因此我可以調用多個網址。我不知道如何處理在單一服務中調用URL。這是我目前的解決方案:在單個服務中處理多個網絡呼叫
public int onStartCommand(Intent intent, int flags, int startId) { SharedPreferences preferences = getSharedPreferences("data", MODE_PRIVATE); String apiKey = preferences.getString("apiKey", null); FetchData data = new FetchData(); data.execute("travel", apiKey); FetchData otherData = new FetchData(); otherData.execute("notifications",apiKey); FetchData barData = new FetchData(); barData.execute("bars", apiKey); checkData(); return START_STICKY; }
這是我的AsyncTask doInBackgroud調用不同的URL:
protected String[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader= null;
String data = null;
try {
selection = params[0];
//url for the data fetch
URL url = new URL("http://api.torn.com/user/?selections="+selection+"&key=*****");
//gets the http result
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//reads the data into an input file...maybe
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
return null;
}
//does something important
reader = new BufferedReader(new InputStreamReader(inputStream));
//reads the reader up above
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
if (buffer.length() == 0) {
return null;
}
data = buffer.toString();
} catch (IOException e) {
return null;
}
finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException ignored) {
}
}
}
如何我不知道,如果我甚至認爲在服務使用的AsyncTask。任何人都可以告訴我什麼是處理這種情況的正確方法