How to send SMS using Twilio in my android application?

后端 未结 6 1778
既然无缘
既然无缘 2020-12-08 17:15

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 cod

6条回答
  •  不思量自难忘°
    2020-12-08 18:03

    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 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() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) Log.d("TAG", "onResponse->success");
                else Log.d("TAG", "onResponse->failure");
            }
    
            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d("TAG", "onFailure");
            }
        });
    }
    
    interface TwilioApi {
        @FormUrlEncoded
        @POST("Accounts/{ACCOUNT_SID}/SMS/Messages")
        Call sendMessage(
                @Path("ACCOUNT_SID") String accountSId,
                @Header("Authorization") String signature,
                @FieldMap Map metadata
        );
    }
    

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

提交回复
热议问题