Android KitKat 4.4 Hangouts no puede manejar el envío de SMS intent


Código para enviar sms que funcionó perfectamente hasta que Android 4.3 (Jelly Bean) dejó de funcionar desde 4.4 (KitKat)

Solo estoy preparando el mensaje de texto para el usuario, pero necesita elegir el número para enviar a

El código que he usado es:

Intent sendIntent = new Intent(Intent.ACTION_VIEW);         
    sendIntent.setData(Uri.parse("sms:"));
    sendIntent.putExtra("sms_body", smsText);

    activity.startActivity(sendIntent);

Desde que dejó de funcionar probé también el ACTION_SEND y ACTION_SENDTO Ambos no funcionaron, también probé el sendIntent.setType("vnd.android-dir/mms-sms");, de nuevo nada funcionó.

Busqué varias respuestas en stackoverflow respuesta 1 y respuesta 2, pero ambas respuestas no están tratando con los requisitos que tengo.

Lo que me gustaría hacer:

  • Enviar sms solo con la aplicación sms, no por todas las aplicaciones que sirven la intención de envío
  • Preparar el texto para el usuario
  • Deje que el usuario elija el número de teléfono para enviar el mensaje a

Para moderadores: No es una pregunta duplicada, ya que las preguntas, no hacen exactamente lo mismo, la necesidad aquí es enviar sms sin número de teléfono, y ninguno de las preguntas y respuestas se referían a eso.

Author: Community, 2013-11-19

3 answers

Adjunté un código que resuelve el problema haciendo lo siguiente:

  • Compruebe la versión del sistema operativo
  • En caso de que la versión anterior (anterior a KitKat), utilice el método antiguo
  • Si es nueva API, compruebe el paquete sms predeterminado. si hay alguno, establézcalo como el paquete; de lo contrario, deje que el usuario elija la aplicación para compartir.

Aquí está el código:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) //At least KitKat
    {
        String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(activity); //Need to change the build to API 19

        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_TEXT, smsText);

        if (defaultSmsPackageName != null)//Can be null in case that there is no default, then the user would be able to choose any app that support this intent.
        {
            sendIntent.setPackage(defaultSmsPackageName);
        }
        activity.startActivity(sendIntent);

    }
    else //For early versions, do what worked for you before.
    {
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.setData(Uri.parse("sms:"));
        sendIntent.putExtra("sms_body", smsText);
        activity.startActivity(sendIntent);
    }
 76
Author: nheimann1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-30 12:08:03

Combinando las soluciones propuestas, lo siguiente proporciona preajustar el destinatario y el texto.

Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) // Android 4.4 and up
{
    String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(activity);

    intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + Uri.encode(toContact.toString())));
    intent.putExtra("sms_body", text);

    if (defaultSmsPackageName != null) // Can be null in case that there is no default, then the user would be able to choose any app that supports this intent.
    {
        intent.setPackage(defaultSmsPackageName);
    }
}
else
{
    intent = new Intent(Intent.ACTION_VIEW);
    intent.setType("vnd.android-dir/mms-sms");
    intent.putExtra("address", toContact.toString());
    intent.putExtra("sms_body", text);
}
activity.startActivity(intent);

El único problema que queda es que terminas en Hangouts (Nexus 5), y es posible que tengas que presionar "atrás" varias veces para cancelar efectivamente el SMS.

 16
Author: johsin18,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-06 06:42:58

Este debería funcionar en todas las versiones de Android y todas las aplicaciones de sms (incluyendo Hangouts).

public static boolean sendSms(Context context, String text, String number) {
    return sendSms(context, text, Collections.singletonList(number));
}

public static boolean sendSms(Context context, String text, List<String> numbers) {

    String numbersStr = TextUtils.join(",", numbers);

    Uri uri = Uri.parse("sms:" + numbersStr);

    Intent intent = new Intent();
    intent.setData(uri);
    intent.putExtra(Intent.EXTRA_TEXT, text);
    intent.putExtra("sms_body", text);
    intent.putExtra("address", numbersStr);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        intent.setAction(Intent.ACTION_SENDTO);
        String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(context);
        if(defaultSmsPackageName != null) {
            intent.setPackage(defaultSmsPackageName);
        }
    } else {
        intent.setAction(Intent.ACTION_VIEW);
        intent.setType("vnd.android-dir/mms-sms");
    }

    try {
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}
 16
Author: Roberto B.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-27 16:37:21