使用smsmsmanager发送消息时出现问题

rryofs0p  于 2021-07-11  发布在  Java
关注(0)|答案(0)|浏览(241)

我是android的初学者。我试着做应用程序发送短信。当我试图用手机发送信息时,应用程序停止工作。模拟器中会出现一条消息:“send sent”。我不明白问题出在哪里。申请代码:

public class MainActivity extends AppCompatActivity {

   private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
   Button sendBtn;
   EditText txtphoneNo;
   EditText txtMessage;
   String phoneNo;
   String message;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       sendBtn = (Button) findViewById(R.id.btnSendSMS);
       txtphoneNo = (EditText) findViewById(R.id.editText);
       txtMessage = (EditText) findViewById(R.id.editText2);

       sendBtn.setOnClickListener(new View.OnClickListener() {
           public void onClick(View view) {
               sendSMSMessage();
           }
       });
   }

   protected void sendSMSMessage() {
       phoneNo = "+48" + txtphoneNo.getText().toString();
       message = txtMessage.getText().toString();

       if (ContextCompat.checkSelfPermission(this,
               Manifest.permission.SEND_SMS)
               != PackageManager.PERMISSION_GRANTED) {
           if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                   Manifest.permission.SEND_SMS)) {
           } else {
               ActivityCompat.requestPermissions(this,
                       new String[]{Manifest.permission.SEND_SMS},
                       MY_PERMISSIONS_REQUEST_SEND_SMS);
           }
       }
   }

   @Override
   public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
       switch (requestCode) {
           case MY_PERMISSIONS_REQUEST_SEND_SMS: {
               if (grantResults.length > 0
                       && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                   SmsManager smsManager = SmsManager.getDefault();
                   smsManager.sendTextMessage(phoneNo, null, message, null, null);
                   Toast.makeText(getApplicationContext(), "SMS sent.",
                           Toast.LENGTH_LONG).show();
               } else {
                   Toast.makeText(getApplicationContext(),
                           "SMS faild, please try again.", Toast.LENGTH_LONG).show();
                   return;
               }
           }
       }

   }
}

我在androidmanifest.xml中写道:

<uses-permission android:name="android.permission.SEND_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>

先谢谢你

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题