短信发送器
采用Activity实现点击事件监听,核心代码只有两行,直接上代码。
MainActivity.java
package com.example.textmessage;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private EditText et_phone;
private EditText et_message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button) findViewById(R.id.bt_send);
bt.setOnClickListener(this);
et_phone = (EditText) findViewById(R.id.et_phone);
et_message = (EditText) findViewById(R.id.et_message);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_send:
String phone = et_phone.getText().toString().trim();
String message = et_message.getText().toString().trim();
if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(message)) {
Toast toast = Toast.makeText(this, "电话号码或短信内容不能为空!", 0);
toast.show();
} else {
//核心代码
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phone, null, message, null, null);
}
}
}
}