简体   繁体   中英

Android — One button send of message

I am trying on the single click on button for my app to send a pre-defined message to a pre-defined number.

  import android.app.Activity;
  import android.view.View.OnClickListener;
  import android.os.Bundle;
  import android.telephony.SmsManager;
  import android.view.View;
  import android.widget.Button;
  import android.widget.Toast;

  public class SendSMSActivity extends Activity {


 Button Send;



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

    Send = (Button) findViewById(R.id.Send);

    buttonSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            String phoneNo = "+0101795123456";
            String mssg = "It is working!";

            try {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNo, null, mssg, null,      null);
                Toast.makeText(getApplicationContext(), "SMS    Sent!"+phoneNo,
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        "SMS failed!"+phoneNo,
                        Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

        }
    });

  }
}

Just getting the toast message as not being sent, this is trying it on actual phone and not emulator, can anyone help point me in the right direction.

将其放在清单中:

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

I suggest use library: https://github.com/klinker41/android-smsmms

implement to gradle

compile 'com.klinkerapps:android-smsmms:5.1.0'

First, create a settings object with all of your required information for what you want to do. If you don't set something, then it will just be set to a default and that feature may not work. For example, if you need MMS, set the MMSC, proxy, and port, or else you will get an error every time.

Settings sendSettings = new Settings();

Next, attach that settings object to the sender

Transaction sendTransaction = new Transaction(mContext, sendSettings);
Now, create the Message you want to send

Message mMessage = new Message(textToSend, addressToSendTo);
mMessage.setImage(mBitmap);   // not necessary for voice or sms messages

And then all you have to do is send the message

sendTransaction.sendNewMessage(message, threadId)

Note: threadId can be nullified (using Transaction.NO_THREAD_ID), but this sometimes results in a new thread being created instead of the message being added to an existing thread

If you want to send MMS messages, be sure to add this to your manifest:

<service android:name="com.android.mms.transaction.TransactionService"/>

Example function:

 public void sendMessage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                com.klinker.android.send_message.Settings sendSettings = new com.klinker.android.send_message.Settings();
                sendSettings.setMmsc(settings.getMmsc());
                sendSettings.setProxy(settings.getMmsProxy());
                sendSettings.setPort(settings.getMmsPort());
                sendSettings.setUseSystemSending(true);

                Transaction transaction = new Transaction(MainActivity.this, sendSettings);

                Message message = new Message(messageField.getText().toString(), toField.getText().toString());

                if (imageToSend.isEnabled()) {
                    message.setImage(BitmapFactory.decodeResource(getResources(), R.drawable.android));
                }

                transaction.sendNewMessage(message, Transaction.NO_THREAD_ID);
            }
        }).start();
    }

Hi I have created this kind of a application please go through below codes and update yours accordingly.

My MainActivity class

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    // Constants
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int REQUEST_PERMISSION_SEND_SMS = 400;

    // UI  Components
    private EditText mEtMobileNumber, mEtMessage;
    private Button mBtnSendMessage;

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

        initView();
    }

    private void initView() {
        mEtMobileNumber = findViewById(R.id.activity_main_et_mobile_number);
        mEtMessage = findViewById(R.id.activity_main_et_message);

        mBtnSendMessage = findViewById(R.id.activity_main_btn_send_message);
        mBtnSendMessage.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_main_btn_send_message:
                checkRuntimePermissionForSMS();
                break;
            default:
                break;
        }
    }


    private void checkRuntimePermissionForSMS(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, REQUEST_PERMISSION_SEND_SMS);
        }else{
            sendMessageFunction(mEtMobileNumber.getText().toString(), mEtMessage.getText().toString());
        }
    }

    private void sendMessageFunction(String phoneNo, String message) {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, message, null, null);
        Toast.makeText(getApplicationContext(), "SMS sent.",
                Toast.LENGTH_LONG).show();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_SEND_SMS: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    sendMessageFunction(mEtMobileNumber.getText().toString(), mEtMessage.getText().toString());
                } else {
                    Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
                    return;
                }
            }
        }

    }
}

My Manifest file I added following permission

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

Thats it, This will work for me,

If you need more help please add a comment to this answer, I will upload a sample project to GitHub and share it with you.

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM