проверка смс на Android без разрешения READ_SMS

Я знаю, что с Android O теперь мы можем читать подтверждение по SMS, не требуя разрешения READ_SMS. Это можно сделать с помощью API createAppSpecificSmsToken.

Но мне нужен полный пример, чтобы продемонстрировать всю процедуру проверки SMS.


person Fartab    schedule 28.05.2017    source источник


Ответы (1)


В этом нет ничего особенного. Позвоните createAppSpecificSmsToken() на SmsManager, поставив PendingIntent. Вы получаете обратно String - жетон. Если устройство получает SMS с этим токеном, ваш PendingIntent запускается, вызывая любой указанный вами компонент.

/***
  Copyright (c) 2017 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  Covered in detail in the book _The Busy Coder's Guide to Android Development_
    https://commonsware.com/Android
 */

package com.commonsware.android.sms.token;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.TextView;

public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SmsManager mgr=SmsManager.getDefault();
    String token=mgr.createAppSpecificSmsToken(buildPendingIntent());
    TextView tv=(TextView)findViewById(R.id.text);

    tv.setText(getString(R.string.msg, token));
  }

  private PendingIntent buildPendingIntent() {
    return(PendingIntent.getActivity(this, 1337,
      new Intent(this, ResultActivity.class), 0));
  }
}

Здесь я показываю токен в виде TextView, поэтому вы можете ввести его в SMS-клиент на другом устройстве и привязать токен к ResultActivity.

Ваш назначенный компонент (например, ResultActivity) получает фактическое SMS-сообщение в своих дополнениях, и вы можете использовать Telephony.Sms.Intents.getMessagesFromIntent(), чтобы добраться до него:

/***
  Copyright (c) 2017 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  Covered in detail in the book _The Busy Coder's Guide to Android Development_
    https://commonsware.com/Android
 */

package com.commonsware.android.sms.token;

import android.app.Activity;
import android.app.PendingIntent;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.TextView;

public class ResultActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv=(TextView)findViewById(R.id.text);

    for (SmsMessage pdu :
      Telephony.Sms.Intents.getMessagesFromIntent(getIntent())) {
      tv.append(pdu.getDisplayMessageBody());
    }
  }
}
person CommonsWare    schedule 28.05.2017
comment
А как насчет серверной стороны .. СМС-токен должен быть в теле СМС? - person Fartab; 28.05.2017
comment
@Fartab: А что насчет серверной части - вы можете использовать сервер, но он не требуется. Не имеет значения, откуда устройство получит SMS с токеном. Это может быть сервер, введенный вручную, с другого устройства или что-то еще. СМС-токен должен быть в теле СМС? -- да. - person CommonsWare; 28.05.2017
comment
используйте следующий учебный документ из Google, здесь - person Sasuke Uchiha; 03.07.2017
comment
@SasukeUchiha - эта статья о совершенно другом API. здесь даже не упоминается метод createAppSpecificSmsToken. - person Dave; 20.04.2018