2017-01-17 1 views
0

У меня возникла проблема с некоторыми вопросами, я получаю тело и адрес sms и отправляю это тело/адрес sms в веб-сервисы, но когда вызывается веб-сервис, значение дублируется, я сталкиваюсь со следующей проблемой:Android Отправить SMS-адрес и тело в веб-сервисе по одному

1- каждый раз, если у меня есть 3 сообщения в моем почтовом ящике, тогда цикл будет выполняться 3 раза, а также есть одно сообщение, которое будет отправляться снова и снова в веб-сервис.

2- я хочу, чтобы, когда я получаю тело и адрес sms, будет вызвана задача asyn, а задача async будет выполняться до конца, после первой итерации снова будет вызываться asyncall для второй итерации и т. Д.

Я знаю, что мой вопрос настолько запутан, но с помощью plz любая помощь будет оценена высоко, ниже мой код.

public void onClick(View v) { 

    ContentResolver contentResolver = getContentResolver(); 
    Cursor cursor = contentResolver.query(Uri.parse("content://sms/inbox"), 
      null, null, null, null); 

    int count = 0; 

    int indexBody = cursor.getColumnIndex(SmsReceiver.BODY); 
    int indexAddr = cursor.getColumnIndex(SmsReceiver.ADDRESS); 

    if (indexBody < 0 || !cursor.moveToFirst()) 
     return; 

    smsList.clear(); 

    do { 
     strmobilenum = cursor.getString(indexAddr); 
     // str = "0" + str.substring(3); 
     strmessagebody = cursor.getString(indexBody); 
     String mb = strmobilenum; 
     String mbody = strmessagebody; 
     //SendSMSToServer(); 
     new AsyncCallWS().execute(); 
    } while (cursor.moveToNext()); 
} 

private class AsyncCallWS extends AsyncTask<String, Void, Void> { 
    @Override 
    protected Void doInBackground(String... params) { 

     try { 

      request = new SoapObject(NAMESPACE, METHOD_NAME); 


      PropertyInfo unameProp = new PropertyInfo(); 
      unameProp.setName("SMSSenderMobileNo");// Define the variable name in 
       String mobnum = strmobilenum;         // the web // service method 
      unameProp.setValue(strmobilenum);// set value for userName variable 
      unameProp.setType(String.class);// Define the type of the variable 
      request.addProperty(unameProp);// Pass properties to the variable 

      PropertyInfo textProp = new PropertyInfo(); 
      textProp.setName("SMSText");// Define the variable name in the web // 
         String msgbody = strmessagebody;    // service method 
      textProp.setValue(strmessagebody);// set value for userName variable 
      textProp.setType(String.class);// Define the type of the variable 
      request.addProperty(textProp);// Pass properties to the variable 

      // SSLConection.allowAllSSL(); 
      envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
      envelope.setOutputSoapObject(request); 
      envelope.dotNet = true; 

      // androidHttpTransport = new HttpTransportSE(URL); 
      androidHttpTransport = new HttpTransportSE(URL, 60000); 



      androidHttpTransport.call(SOAP_ACTION, envelope); 
      SoapPrimitive response = (SoapPrimitive) envelope.getResponse(); 

      String jsonResponse = ""; 
      jsonResponse = response.toString(); 

      // A JSONTokener is needed in order to use JSONObject correctly 
      JSONTokener jsonTokener = new JSONTokener(jsonResponse); 
      // Pass a JSONTokener to the JSONObject constructor 
      JSONObject jsonObj = new JSONObject(jsonTokener); 
      JSONArray data = jsonObj.getJSONArray("FeedSMS"); 

      if (data != null) { 

       // looping through All nodes 
       for (int i = 0; i < data.length(); i++) { 
        JSONObject c = data.getJSONObject(i); 
        RetVal = c.getString("RetVal"); 
        RetDes = c.getString("RetDes"); 

       } 

       /* 
       * Toast.makeText(getBaseContext(), "Success", 
       * Toast.LENGTH_LONG).show(); 
       */ 

      } else { 


     } catch (Exception e) { 
      // alertDialog(e.toString()); 
      /* 
      * Toast.makeText(getApplicationContext(), e.getMessage(), 
      * Toast.LENGTH_LONG).show(); 
      */ 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     // Log.i(TAG, "onPostExecute"); 
     // tv.setText(fahren + "° F"); 

     pDialog.dismiss(); 

     if (RetVal != null) { 

      // Toast.makeText(getApplicationContext(), message, 
      // Toast.LENGTH_SHORT).show(); 

      if (RetVal.equalsIgnoreCase("T")) { 

       alertDialog(RetDes); 

      } else { 

       alertDialog(RetDes); 

      } 
     } else { 
      //alertDialog("server error"); 
     } 
    } 

    @Override 
    protected void onPreExecute() { 

     pDialog.setMessage("Sending SMS..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    @Override 
    protected void onProgressUpdate(Void... values) { 
     // Log.i(TAG, "onProgressUpdate"); 
    } 

} 

ответ

0

Вы получаете индекс вне цикла в то время как

int indexBody = cursor.getColumnIndex(SmsReceiver.BODY); 
int indexAddr = cursor.getColumnIndex(SmsReceiver.ADDRESS); 

if (indexBody < 0 || !cursor.moveToFirst()) 
    return; 

выше indexBody и indexAddr всегда будет содержать значения для первых смс, как положение курсора 0 в первый раз. Написать выше код в сделать петлю ниже

do 
{ 
    int indexBody = cursor.getColumnIndex(SmsReceiver.BODY); 
    int indexAddr = cursor.getColumnIndex(SmsReceiver.ADDRESS); 
    if (indexBody < 0 || !cursor.moveToFirst()) 
     return; 
    strmobilenum = cursor.getString(indexAddr); 
    // str = "0" + str.substring(3); 
    strmessagebody = cursor.getString(indexBody); 
    String mb = strmobilenum; 
    String mbody = strmessagebody; 
    //SendSMSToServer(); 
    new AsyncCallWS().execute(); 
} 
+0

я просто хочу, что 1-го тела смс отправить в веб-сервис успешно, после того, как успешно отправки 1-го смс, то второй будет отправить в веб-службы и так пока все sms не будут прочитаны и не будут отправлены на веб-службу. – newOnAndroid

+0

Должен быть какой-то более простой способ его достижения, но насколько я знаю, что вы можете сделать, получите все цифры и sms-объекты из курсора и сохраните их в arraylist. Затем запустите свой asyncTask, добавив значение от arraylist, когда в ответ вы получите statusCode = 200, снова вызовите asyncTask со следующей позицией в arraylist –

+0

, вы нашли ответ полезным? Если да, то, пожалуйста, примите ответ, а если нет, можете ли вы сказать мне, как вы решили свою проблему? –

Смежные вопросы