我是Android新手,我正在使用按鈕單擊以使用GCM發送推送通知。我有執行GCM推送的功能。我需要將它從函數轉換爲AsyncTask類。我在互聯網上看到了很多,但仍然面臨困境。任何人都可以幫我轉換它嗎?如何在AsyncTask中執行網絡操作 - Android
推送功能
public void sendPush(int position){
pushProgressBar.setVisibility = (View.VISIBLE)
try {
// Prepare JSON containing the GCM message content. What to send and where to send.
JSONObject jGcmData = new JSONObject();
JSONObject jData = new JSONObject();
jData.put("message", "Hello");
// Where to send GCM message.
TinyDB tinyDB = new TinyDB(mContext);
ArrayList<String> userToken = tinyDB.getListString("tokenList");
String tokenToSend = userToken.get(position);
jGcmData.put("to", tokenToSend);
// What to send in GCM message.
jGcmData.put("data", jData);
// Create connection to send GCM Message request.
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + R.string.apikey);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send GCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jGcmData.toString().getBytes());
// Read GCM response.
InputStream inputStream = conn.getInputStream();
String resp = IOUtils.toString(inputStream);
System.out.println(resp);
System.out.println("Check your device/emulator for notification or logcat for " +
"confirmation of the receipt of the GCM message.");
pushProgressBar.setVisibility = (View.GONE)
} catch (IOException e) {
System.out.println("Unable to send GCM message.");
System.out.println("Please ensure that API_KEY has been replaced by the server " +
"API key, and that the device's registration token is correct (if specified).");
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
在此先感謝。希望我從中學習。
使用齊射。 https://developer.android.com/training/volley/index.html – ElDuderino
我不想使用它,我只是想將此功能轉換爲AsyncTask。如果你知道它。請幫助。不要誤導我。 –
那麼......你的asynctask問題是什麼?試過什麼......?把網絡部分放在doInBackground中......就是這樣。 – ElDuderino