2013-06-28 206 views
0

我需要這個類的幫助,它甚至不返回消息的SID。我的應用程序的目的是全天候運行,並在第一次啓動時發送消息,但很快就無法發送消息。每次發送消息時,是否需要重新制作TwilioRestClient對象?Twilio API;短信不發送

public class Twilio { 

public static final String ACCOUNT_SID = "VALID SID"; 
public static final String ACCOUNT_AUTH = "VALID AUTH"; 

private static Twilio instance; 

public static Twilio getInstance() { 
    return instance == null ? (instance = new Twilio()) : instance; 
} 

private TwilioRestClient client; 
private SmsFactory smsFactory; 

private Map<String, String> defaultProps = new HashMap<>(); 

public Twilio() { 
    defaultProps.put("From", "VALID TWILIO NUMBER"); 
    client = new TwilioRestClient(ACCOUNT_SID, ACCOUNT_AUTH); 
} 

public SmsFactory getSMSFactory() { 
    return smsFactory == null ? (smsFactory = client.getAccount().getSmsFactory()) : smsFactory; 
} 

private Sms buildSMS(String recipient, String body) { 
    Sms sms = null; 
    defaultProps.put("To", recipient); 
    defaultProps.put("Body", body); 
    try { 
     sms = getSMSFactory().create(defaultProps); 
    } catch (TwilioRestException e) { e.printStackTrace(); } 
    return sms; 
} 

public String[] sendSMS(String body, String... recipients) { 
    List<String> sids = new ArrayList<>(); 
    for (String r : recipients) 
     sids.add(buildSMS(r, body).getSid()); 
    return sids.toArray(new String[sids.size()]); 
} 

}

+0

當你說「無法發送消息」你能更清楚嗎? –

+0

它甚至不會將其記錄爲網站日誌窗格上發送的消息。它像它甚至沒有提出要求。 – TeJanca

回答

0

你可以試試這個代碼,如果它幫助。它對我的工作很好。

public boolean sendSMS(String to, String from, String text){ 
    try { 
     String[] toarr = to.split(","); 
     TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN); 
     if(toarr.length > 0){ 
      for (int i = 0; i < toarr.length; i++) { 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("To", toarr[i])); 
       params.add(new BasicNameValuePair("From", from)); 
       params.add(new BasicNameValuePair("Body", text)); 
       MessageFactory messageFactory = client.getAccount().getMessageFactory(); 
       com.twilio.sdk.resource.instance.Message message = messageFactory.create(params); 
      } 
     } 
    } 
    catch (TwilioRestException tex) { 
     tex.printStackTrace(); 
    } 
    return true; 
}