通过服务发送短信

时间:2019-06-11 11:31:04

标签: java android

我试图在比赛发生时通过我的服务发送短信

我试图在服务中建立接口,并在其他活动中编写函数。但是我不知道如何在服务中调用我的函数,以及是否还有其他解决方案。

public interface smsSender{
       void sendSms(String phoneNum);
   } //the interface in my service

//in other class
@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)
               {
                   sendSms("00000000");
               }
       }
   }

   @Override
   public void sendSms(String phoneNum) {
       int permissionCheck= ContextCompat.checkSelfPermission(this, android.Manifest.permission.SEND_SMS);
       if(permissionCheck == PackageManager.PERMISSION_GRANTED)
       {
           final SmsManager smgr = SmsManager.getDefault();

           DatabaseReference database = FirebaseDatabase.getInstance().getReference();

           smgr.sendTextMessage(phoneNum,null,"String in sms",null,null);




       }
       else
       {
           ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.SEND_SMS},0);
       }

   }


如何从服务中调用此功能,或者有更好的方法从服务中发送短信

1 个答案:

答案 0 :(得分:0)

首先确保在清单文件中将sens sms权限声明为

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

接下来要使用SMSManager API发送短信

SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(MobileNumber,null,Message,null,null);

请找到以下示例代码

 try{
                SmsManager smgr = SmsManager.getDefault();
                smgr.sendTextMessage(txtMobile.getText().toString(),null,txtMessage.getText().toString(),null,null);
                Toast.makeText(MainActivity.this, "SMS Sent Successfully", Toast.LENGTH_SHORT).show();
            }
            catch (Exception e){
                Toast.makeText(MainActivity.this, "SMS Failed to Send, Please try again", Toast.LENGTH_SHORT).show();
            }

在服务中,使用以下代码

 SmsManager sms = SmsManager.getDefault();
                                    // if message length is too long messages are divided
                                    List<String> messages = sms.divideMessage(message);
                                    for (String msg : messages) {

                                        PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, new Intent("SMS_SENT"), 0);
                                        PendingIntent deliveredIntent = PendingIntent.getBroadcast(context, 0, new Intent("SMS_DELIVERED"), 0);
                                        sms.sendTextMessage(phone, null, msg, sentIntent, deliveredIntent);

                                        Toast.makeText(context, "SMS Sent to: " + number, Toast.LENGTH_SHORT).show();
 }