Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send SMS using Twilio in my android application?

In my android application I have created one button, when I had pressed on the button I want to send message.So for that I have created one java class and written twilio code.

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();
                }

when I am using the above code it showing some error like java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager

I have added only one jar file in lib folder as " twilio-java-sdk-3.3.10-jar-with-dependencies.jar ".

please tell me what can I do?

like image 223
Hanuman Avatar asked Jan 23 '15 11:01

Hanuman


People also ask

How we can send and receive SMS in android application?

The user can tap the messaging icon in your app to send the message. In the messaging app launched by the intent, the user can tap to send the message, or change the message or the phone number before sending the message. After sending the message, the user can navigate back to your app using the Back button.

How do I send SMS from app?

icon from the toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application. Now you can enter a desired mobile number and a text message to be sent on that number. Finally click on Send SMS button to send your SMS.

Can I send SMS from Twilio console?

Using Twilio's REST API, you can send outgoing SMS messages from your Twilio phone number to mobile phones around the globe. In this guide, we'll explore how you can use Twilio's Programmable Messaging API to: Send an SMS message from your Twilio phone number.


2 Answers

My method, using OkHttp:

1. Prerequisites

Gradle:

dependencies {    
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
}

Manifest:

<uses-permission android:name="android.permission.INTERNET"/>

Permission in activity:

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build() );
}

2. Code

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(); }

}

I used Allu code for generathing authorization in header

like image 70
thorin86 Avatar answered Nov 11 '22 14:11

thorin86


This solution with 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
    );
}

Dependencies for build.gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'

like image 32
TarikW Avatar answered Nov 11 '22 16:11

TarikW