Android – Listen For Incoming SMS Messages

后端 未结 9 1472
情话喂你
情话喂你 2020-11-22 07:06

I am trying to create an application for monitoring incoming SMS messages, and launch a program via incoming SMS, also it should read the content from the SMS.

Workf

9条回答
  •  囚心锁ツ
    2020-11-22 07:34

    The accepted answer is correct and works on older versions of Android where Android OS asks for permissions at the app install, However on newer versions Android it doesn't work straight away because newer Android OS asks for permissions during runtime when the app requires that feature. Therefore in order to receive SMS on newer versions of Android using technique mentioned in accepted answer programmer must also implement code that will check and ask for permissions from user during runtime. In this case permissions checking functionality/code can be implemented in onCreate() of app's first activity. Just copy and paste following two methods in your first activity and call checkForSmsReceivePermissions() method at the end of onCreate().

        void checkForSmsReceivePermissions(){
        // Check if App already has permissions for receiving SMS
        if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.RECEIVE_SMS") == PackageManager.PERMISSION_GRANTED) {
            // App has permissions to listen incoming SMS messages
            Log.d("adnan", "checkForSmsReceivePermissions: Allowed");
        } else {
            // App don't have permissions to listen incoming SMS messages
            Log.d("adnan", "checkForSmsReceivePermissions: Denied");
    
            // Request permissions from user 
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECEIVE_SMS}, 43391);
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 43391){
            if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Log.d("adnan", "Sms Receive Permissions granted");
            } else {
                Log.d("adnan", "Sms Receive Permissions denied");
            }
        }
    }
    

提交回复
热议问题