我的应用未从API 23合法地读取短信

时间:2019-01-21 12:48:45

标签: java android android-studio sms

我正在开发一个应用程序,该应用程序必须完全像在Whatsapp上注册时一样通过SMS读取确认码。它适用于Android 5及更低版本,但从6版本开始,该应用程序无法读取短信。

下面是在主函数中调用的类。它会自动读取收到的SMS消息:

public class SmsReceiver extends BroadcastReceiver {
    private static SmsListener mListener;
    //add...
    private static final String 
    TAG = SmsReceiver.class.getSimpleName();
    public static final String pdu_type = "pdus";
    //add..
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle data = intent.getExtras();
        Object[] pdus = (Object[]) data.get("pdus");
        String format = data.getString("format");         
//Toast.makeText(context,"coollll:" + pdus,Toast.LENGTH_LONG).show();
        if (pdus!=null){
           // 
Toast.makeText(context,"noooooooo",Toast.LENGTH_LONG).show();

            boolean isVersionM= (Build.VERSION.SDK_INT >= 
Build.VERSION_CODES.M);
                for (int i=0; i<pdus.length; i++){
                    if (isVersionM){
                        SmsMessage smsMessage = 
SmsMessage.createFromPdu((byte[]) pdus[i],format);
                    String sender = smsMessage.getDisplayOriginatingAddress();
                        if(sender.equals("myProjet")){
                            String messageBody = smsMessage.getMessageBody();
                            mListener.messageReceived(messageBody);
                        }
                }else {
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    String sender = smsMessage.getDisplayOriginatingAddress();
                    if(sender.equals("projet")){
                        String messageBody = smsMessage.getMessageBody();
                        mListener.messageReceived(messageBody);
                    }
                }
            }
    }
}
public static void bindListerner(SmsListener listener){
    mListener = listener;
}
}

下面是SmsListener.java接口,用于侦听传入消息:

public interface SmsListener {
    public void messageReceived(String messageText);
}

以下是处理收到的SMS的活动:

public class CodeConfirmation extends Activity {
    private String telephone;
    private TextView tel, textcode, textCount, textSendAgainSms;
    private RequestQueue requestQueue;
    private StringRequest stringRequest;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_code_confirmation);
        final Pinview pin = (Pinview) findViewById(R.id.pinview);
        pin.setPinBackgroundRes(R.drawable.sample_background);

        countTime();

        requestQueue= Volley.newRequestQueue(this);

        Intent intent= getIntent();
        final String codeGenere= 
getIntent().getExtras().getString("code");
        telephone= getIntent().getExtras().getString("telephone");
        Toast.makeText(CodeConfirmation.this, codeGenere, 
Toast.LENGTH_SHORT).show();
        // on affiche le numéro de l'utilisateur dans la vue

        tel =(TextView)findViewById(R.id.my_number);
        textcode=(TextView)findViewById(R.id.text);
        tel.setText(getString(R.string.your_tel)+ telephone);
        textcode.setText(getString(R.string.code_confirmation));
        textCount=(TextView)findViewById(R.id.textCount);
        textSendAgainSms=(TextView)findViewById(R.id.send_code_agent);

        textSendAgainSms.setOnClickListener(new View.OnClickListener() {
            @Override
        public void onClick(View v) {
                textSendAgainSms.setText(null);
                countTime();
            }
        });

        SmsReceiver.bindListerner(new SmsListener() {
            @Override
            public void messageReceived(String messageText) {
Toast.makeText(CodeConfirmation.this,"Message:" + messageText,Toast.LENGTH_LONG).show();
                    if (messageText.compareToIgnoreCase(codeGenere)==0){
                    pin.setValue(messageText);
Toast.makeText(CodeConfirmation.this, getString(R.string.succes_code), Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
}
});

        /*
        *Lorsque l'utilisateur entre le code à 5 chiffres
         */
        pin.setPinViewEventListener(new 
Pinview.PinViewEventListener() {
            @Override
            public void onDataEntered(Pinview pinview, boolean b) {
                final String code= pinview.getValue();
                //Toast.makeText(CodeConfirmation.this, code, Toast.LENGTH_SHORT).show();

            if (code.compareToIgnoreCase(codeGenere)==0){
                Toast.makeText(CodeConfirmation.this,getString(R.string.succes_code), Toast.LENGTH_SHORT).show();
                finish();
                startActivity(new Intent(getApplicationContext(),LoginActivity.class));

            }
            else{
                Toast.makeText(CodeConfirmation.this,getString(R.string.wrong_code), Toast.LENGTH_SHORT).show();

            }

        }
    });
}

public void countTime(){
    new CountDownTimer(30000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            textCount.setText(getString(R.string.TimeCount)+":"+millisUntilFinished/1000);
        }

        @Override
        public void onFinish() {
            textSendAgainSms.setText(getString(R.string.send_code_agent));
        }
    }.start();
}
public void CheckNumber(final String telephone){
    stringRequest= new StringRequest(Request.Method.POST, BuildConfig.server + "register", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);
                String objetJson= jsonObject.getString("success");
                //Toast.makeText(getApplicationContext(),"response-> : "+jsonObject.getString("success"), Toast.LENGTH_SHORT).show();

                if(objetJson.equals("true")){
                    /*Toast.makeText(getApplicationContext(), "code-> "+jsonObject.getString("code"), Toast.LENGTH_LONG).show();
                    Toast.makeText(getApplicationContext(), "telephone-> "+jsonObject.getString("telephone"), Toast.LENGTH_LONG).show();*/

                    //startActivity(new Intent(getApplicationContext(),CodeConfirmation.class));
                }
                else if(objetJson.equals("false")){
                    Toast.makeText(getApplicationContext(),"error", Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(),"Aucune connexion internet  " ,Toast.LENGTH_SHORT).show();
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("telephone", telephone);
            return hashMap;
        }
    };
    requestQueue.add(stringRequest);
}

}

这是我的AndroidManifest.xml文件的样子:

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission 
    android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission 
android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".connexion.LoginActivity"
        android:label="@string/title_activity_login"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".connexion.CodeConfirmation"
        android:label="@string/title_activity_code_confirmation" />
    <receiver
        android:name=".sms.SmsReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
              <action 
    android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>
    </application>
</manifest>

1 个答案:

答案 0 :(得分:0)

在新的android api中,您当然需要Manifest的权限,但是需要实现运行时权限,也许可以将其放在您的第一个Activity中。

Look this link

Examples to do runtime permission