How can I read SMS messages from the device programmatically in Android?

后端 未结 11 2352
情深已故
情深已故 2020-11-22 02:48

I want to retrieve the SMS messages from the device and display them?

11条回答
  •  孤独总比滥情好
    2020-11-22 03:14

    Step 1: first we have to add permissions in manifest file like

    
    
    

    Step 2: then add service sms receiver class for receiving sms

    
        
            
        
    
    

    Step 3: Add run time permission

    private boolean checkAndRequestPermissions()
    {
        int sms = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
    
        if (sms != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }
    

    Step 4: Add this classes in your app and test Interface class

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

    SmsReceiver.java

    public class SmsReceiver extends BroadcastReceiver {
        private static SmsListener mListener;
        public Pattern p = Pattern.compile("(|^)\\d{6}");
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle data  = intent.getExtras();
            Object[] pdus = (Object[]) data.get("pdus");
            for(int i=0;i

提交回复
热议问题