0

I am a newbie in android app making and am struggling to find a way to send SMS to a phone number that has been saved using SharedPreferences.In the MainActivity, I have saved the phone number and user name in a file called saveddata. Then in another activity called SMS,I am trying to send an SMS to the saved phone number after a button labeled as sendbutton is clicked. In android manifest I have mentioned SEND_SMS permission.

The build and installation are successful, but the app is crashing. Please help and thanks in advance. This is the code :

public class SMS extends AppCompatActivity {
    private TextView header;
    private Button sendbutton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);
        header = (TextView) findViewById(R.id.headerText);
        sendbutton = (Button) findViewById(R.id.button);
        sendbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int permissionCheck = ContextCompat.checkSelfPermission(SMS.this, Manifest.permission.SEND_SMS);


                if( permissionCheck == PackageManager.PERMISSION_GRANTED) {
                    MyMessage();
                } else {
                    ActivityCompat.requestPermissions(SMS.this, new String[]{Manifest.permission.SEND_SMS}, 0);
                }

            }


        });


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0:
                if (grantResults.length >= 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    MyMessage();
                } else {
                    Toast.makeText(getApplicationContext(), "Permission needed to send SMS", Toast.LENGTH_SHORT).show();
                }

                break;
        }

    }

    private void MyMessage() {
        //SharedPreferences result = getSharedPreferences("saveddata", MODE_PRIVATE);
        SharedPreferences result = getSharedPreferences("saveddata", MODE_PRIVATE);
        String savedname = result.getString("NAME", "name not found");
        String savedphone = result.getString("PHONE", "phone not found");

        String message = "I need help" + " " + savedname ;
        if (!savedphone.equals("")) {

            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(savedphone, null, message, null, null);
            Toast.makeText(getApplicationContext(), "SMS sent", Toast.LENGTH_SHORT).show();

        } else {
            Toast.makeText(getApplicationContext(), "Phone number or name n.a.", Toast.LENGTH_SHORT).show();
        }
    }
}

I am getting this message in logcat after pressing the send button:

--------- beginning of crash 2020-02-12 09:11:20.331 28633-28633/com.example.testing E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.testing, PID: 28633 java.lang.SecurityException: Neither user 10086 nor current process has android.permission.READ_PHONE_STATE. at android.os.Parcel.readException(Parcel.java:1942) at android.os.Parcel.readException(Parcel.java:1888) at com.android.internal.telephony.ISms$Stub$Proxy.sendTextForSubscriber(ISms.java:789) at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:329) at android.telephony.SmsManager.sendTextMessage(SmsManager.java:312) at com.example.testing.SMS.MyMessage(SMS.java:77) at com.example.testing.SMS.access$000(SMS.java:18) at com.example.testing.SMS$1.onClick(SMS.java:36) at android.view.View.performClick(View.java:6256) at android.view.View$PerformClick.run(View.java:24701) at android.os.Handler.handleCallback(Handler.java:789) at android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Molly
  • 1,887
  • 3
  • 17
  • 34

2 Answers2

0

It seems that your app doesn't have permission to send sms.Add the permission in manifest file

0

You can use Dexter to request both permissions

In build.gradle add:

implementation 'com.karumi:dexter:5.0.0'

And use it in your activity as:

val requiredPermissions =listOf(Manifest.permission.SEND_SMS,
                Manifest.permission.READ_PHONE_STATE)

Dexter.withActivity(this)
     .withPermissions(requiredPermissions)
     .withListener(object : MultiplePermissionsListener {
        override fun onPermissionRationaleShouldBeShown(
             permissions: MutableList<PermissionRequest>?,
                    token: PermissionToken?
             ) {
                    /* ... */
                }

        override fun onPermissionsChecked(report: MultiplePermissionsReport) = 
             if (report.isAnyPermissionPermanentlyDenied) {
                toast("You should grant all permissions") 
             } else {
                toast("All permissions granted now send sms here")
              }).check()

  • Sorry, I am getting lots of errors when I used the Dexter code.I added Dexter implementation in build.gradle Module app under dependencies. Then in the SMS.java when I copied the code it could not resolve Dexter, val, MultiplePermissionsListener etc. Am at my wit's end. – Android newbie Feb 21 '20 at 04:47