¿Cómo enviar SMS usando Twilio en mi aplicación Android?
En mi aplicación Android he creado un botón, cuando había presionado el botón que quiero enviar message.So para que he creado una clase de Java y escrito código twilio.
final TwilioRestClient client = new TwilioRestClient( ACCOUNT_SID, AUTH_TOKEN); // Get the main account (The one we used to authenticate the // client) final Account mainAccount = client.getAccount(); final SmsFactory messageFactory = mainAccount.getSmsFactory(); final Map<String, String> messageParams = new HashMap<String, String>(); messageParams.put("To", "+912342423423"); messageParams.put("From", "+132432432434"); messageParams.put("Body", "This is my message"); try { messageFactory.create(messageParams); } catch (TwilioRestException e) { e.printStackTrace(); }
Cuando estoy usando el código anterior que muestra algunos errores como java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager
- La llamada de Twilio no funciona en iOS y Android en react-native
- No se puede registrar SIP con Twilio SDK
- Problema para implementar twilio api en android
- JNI ERROR DETECTADO EN APLICACIÓN: entrada no es válida UTF-8 modificado: byte de inicio ilegal 0xfc.
- Twilio Client Android v1.2.8 se bloquea cuando el dispositivo cliente realiza una llamada y el método onDisconnected de ConnectionListener no se llama automáticamente
Solo he añadido un archivo jar en la carpeta lib como " twilio-java-sdk-3.3.10-jar-with-dependencies.jar ".
Por favor dime que puedo hacer
- La aplicación no debe mostrarse en la lista de aplicaciones recientes después de terminar la actividad si la aplicación no estaba mostrando la lista de aplicaciones recientes anteriormente.
- Twilio vs google voz api para SMS
- Estoy trabajando con Twilio android SDK, Cuando hago clic en el botón de bloqueo siempre recibiendo error - no es capaz de desconectar la llamada después de marcar?
- Reacciona Nativo y Twilio en Android
- Twilio Android Client - Cómo renovar el token de capacidad para el dispositivo que recibe la llamada entrante
- Recibir llamadas durante una hora usando Twilio
- Android Twilio No se puede crear / enviar REGISTRO: El objeto está ocupado (PJSIP_EBUSY)?
- Verificar el usuario durante la suscripción enviando y recibiendo sms a través de Twilio
He utilizado el método de HttpPost para enviar sms en que he pasado mi url con base de autenticación aquí es mi código
HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/SMS/Messages"); String base64EncodedCredentials = "Basic " + Base64.encodeToString( (ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP); httppost.setHeader("Authorization", base64EncodedCredentials); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("From", "+123424353534")); nameValuePairs.add(new BasicNameValuePair("To", "+914342423434")); nameValuePairs.add(new BasicNameValuePair("Body", "Welcome to Twilio")); httppost.setEntity(new UrlEncodedFormEntity( nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); System.out.println("Entity post is: " + EntityUtils.toString(entity)); } catch (ClientProtocolException e) { } catch (IOException e) { } }
Está funcionando bien.
Esta solución con Retrofit
public static final String ACCOUNT_SID = "accountSId"; public static final String AUTH_TOKEN = "authToken"; private void sendMessage() { String body = "Hello test"; String from = "+..."; String to = "+..."; String base64EncodedCredentials = "Basic " + Base64.encodeToString( (ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP ); Map<String, String> data = new HashMap<>(); data.put("From", from); data.put("To", to); data.put("Body", body); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.twilio.com/2010-04-01/") .build(); TwilioApi api = retrofit.create(TwilioApi.class); api.sendMessage(ACCOUNT_SID, base64EncodedCredentials, data).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) Log.d("TAG", "onResponse->success"); else Log.d("TAG", "onResponse->failure"); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.d("TAG", "onFailure"); } }); } interface TwilioApi { @FormUrlEncoded @POST("Accounts/{ACCOUNT_SID}/SMS/Messages") Call<ResponseBody> sendMessage( @Path("ACCOUNT_SID") String accountSId, @Header("Authorization") String signature, @FieldMap Map<String, String> metadata ); }
Dependencias para build.gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'
Mi método, usando OkHttp :
1. Requisitos previos
Gradle:
dependencies { compile 'com.squareup.okhttp3:okhttp:3.4.1' }
Manifiesto:
<uses-permission android:name="android.permission.INTERNET"/>
Permiso en actividad:
if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build() ); }
2. Código
private void sendSms(String toPhoneNumber, String message){ OkHttpClient client = new OkHttpClient(); String url = "https://api.twilio.com/2010-04-01/Accounts/"+ACCOUNT_SID+"/SMS/Messages"; String base64EncodedCredentials = "Basic " + Base64.encodeToString((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP); RequestBody body = new FormBody.Builder() .add("From", fromPhoneNumber) .add("To", toPhoneNumber) .add("Body", message) .build(); Request request = new Request.Builder() .url(url) .post(body) .header("Authorization", base64EncodedCredentials) .build(); try { Response response = client.newCall(request).execute(); Log.d(TAG, "sendSms: "+ response.body().string()); } catch (IOException e) { e.printStackTrace(); } }
Utilicé el código Allu para generar la autorización en el encabezado
Twilio Java SDK tiene dependencias de terceros sin ellos no va a funcionar. Las dependencias son: 1. Httpcore 2. Httpclient 3. Commons lang 4. Json simple 5. Jackson No muy seguro si usted los necesita todos, pero por lo menos ahora usted falta httpcore
Debe utilizar el proyecto BasicPhone de Twilio SDK. He intentado llamar y ahora puedo llamar también. Este proyecto tiene todos los métodos y funciones que necesita para llamar y enviar SMS. En primer lugar, necesita un servicio web PHP para obtener un token de capacidad y pasar ese script PHP a su aplicación.
Así resolví mi necesidad. Public class TwilioAsyncTask extends AsyncTask {
Context context; ProgressDialog progressDialog; public TwilioAsyncTask(Context context) { this.context = context; } @Override protected String doInBackground(String... strings) { // HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "https://api.twilio.com/2010-04-01/Accounts/AC_yourACCOUNT_SID_9b/SMS/Messages"); String base64EncodedCredentials = "Basic " + Base64.encodeToString( (ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP); httppost.setHeader("Authorization", base64EncodedCredentials); try { int randomPIN = (int) (Math.random() * 9000) + 1000; String randomVeriValue = "" + randomPIN; // these are for control in other anctivity used sharepreference editorTwilio.putString("twilio_veri_no", randomVeriValue); editorTwilio.commit(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("From", "+148******")); // what number they gave you nameValuePairs.add(new BasicNameValuePair("To", "+90" + phoneNo)); // your phone or our customers nameValuePairs.add(new BasicNameValuePair("Body", "Your verification number is : " + randomVeriValue)); httppost.setEntity(new UrlEncodedFormEntity( nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); System.out.println("Entity post is: " + EntityUtils.toString(entity)); // Util.showMessage(mParentAct, "Welcome"); } catch (ClientProtocolException e) { } catch (IOException e) { } // return "Executed"; } @Override protected void onPostExecute(String result) { // execution of result of Long time consuming operation //progressDialog.dismiss(); } @Override protected void onPreExecute() { progressDialog = ProgressDialog.show(context, "", " Wait for "); } @Override protected void onProgressUpdate(String... text) { // Things to be done while execution of long running operation is in // progress. For example updating ProgessDialog } } And call your Task TwilioAsyncTask task = new TwilioAsyncTask(CountryAndPhone.this); task.execute();
- Renombrar completamente un proyecto en Eclipse
- Cómo detectar el contacto del usuario con el espacio telefónico usando JS