Receive an read SMS with correct encoding and convert to UTF8

喜夏-厌秋 提交于 2019-12-13 01:43:37

问题


I am writing a BroadcastReceiver to receive SMS messages. I will need to compare the message with a string that was set by the user in the settings, but the string can be non-ASCII. The below code works only for SMS-es that contain only ASCII characters. How can I convert the message to UTF8 encoding?

public class SmsReceiver extends BroadcastReceiver {
    final static String TAG = "SmsReceiver";

    public SmsReceiver() {
    }

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (int i = 0; i < pdusObj.length; i++) {

                    final SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    final String senderNum = currentMessage.getDisplayOriginatingAddress();

                    final String message = currentMessage.getDisplayMessageBody();

                    Log.i(TAG, "senderNum: " + senderNum + "; message: " + message);

update:

it seems that the same code works on my Nexus5, but doesn't work in the emulator with API 10.

The text I sent: שלום

The text I received: éRΨ¿Ñ u$


回答1:


For the record, if someone else gets into similar problems, it seems to be a bug in the emulators. I opened a ticket for android emulator: https://code.google.com/p/android/issues/detail?id=202723



来源:https://stackoverflow.com/questions/35797212/receive-an-read-sms-with-correct-encoding-and-convert-to-utf8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!