本帖最后由 huyang936 于 2015-2-23 22:13 编辑
- package cn.itcast.sendMess;
- import android.app.Activity;
- import android.os.Bundle;
- import android.telephony.SmsManager;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- public class MainActivity extends Activity {
- private EditText et_number;
- private EditText et_messa;
- private String number;//在外部类声明number
- private String messa;//在外部类声明message
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- // 获取号码文本对象
- et_number = (EditText) findViewById(R.id.editText1);
- // 获取信息文本对象
- et_messa = (EditText) findViewById(R.id.editText2);
- //获取电话号码
- number = et_number.getText().toString();
- //获取发送信息
- messa = et_messa.getText().toString();
- //获取按钮对象
- Button bt_send = (Button) findViewById(R.id.button1);
- //设置点击事件
- bt_send.setOnClickListener(new MyLisener());
-
- }
-
- class MyLisener implements OnClickListener
- {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- SmsManager smsManager = SmsManager.getDefault();
- smsManager.sendTextMessage(number, null, messa, null, null);
- }
- }
- }
复制代码 上面的代码崩溃掉了,如图:经验证是因为
电话号码number,和发送的消息messa声明的位置引起的
(为什么不可以呢?大神求解释!!!)
一下代码正常:
电话号码number,和发送的消息messa在内部类中获取
package cn.itcast.sendMess;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText et_number;
private EditText et_messa;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取号码文本对象
et_number = (EditText) findViewById(R.id.editText1);
// 获取信息文本对象
et_messa = (EditText) findViewById(R.id.editText2);
//获取按钮对象
Button bt_send = (Button) findViewById(R.id.button1);
//设置点击事件
bt_send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//获取电话号码
String number = et_number.getText().toString();//在此处获取number
//获取发送信息
String messa = et_messa.getText().toString();//在此处获取message
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, messa, null, null);
}
});
}
|
|