我有一个EditView,用户应该输入一个电话号码。然后,我想接听该电话号码并在另一项活动中拨打/发送电话。我怎么能这样做?
这是我的主要活动的一部分:
EditText editText = (EditText) findViewById(R.id.editText1);
editText.setOnClickListener(this);
}
public void onClick(View src) {
Intent serviceIntent = new Intent(this, MyService.class);
switch (src.getId()) {
case R.id.button1:
Log.d(TAG, "onClick: starting service");
EditText editText = (EditText) findViewById(R.id.editText1);
if (editText.getText().toString()==""){
Toast.makeText(getApplicationContext(), "Please enter a phone number", Toast.LENGTH_SHORT).show();
} else {
pnumber = editText.getText().toString();
startService(serviceIntent);
serviceIntent.putExtra(number, pnumber);
break;
}
}
}
}
然后在我的其他活动中:
Bundle extras = this.getIntent().getExtras(); {
if(extras !=null)
{
String newnumber = extras.getString(number,pnumber);
Uri number = Uri.parse(newnumber);
Intent callIntent = new Intent(Intent.ACTION_CALL, number);
Intent textIntent = new Intent(Intent.ACTION_SENDTO, number);
}
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.button2:
//Log.d(TAG, "onClick: starting call");
startActivity(callIntent);
break;
case R.id.button3:
//Log.d(TAG, "onClick: start text message");
startActivity(textIntent);
break;
}
}
}
Uri不断解析“newnumber”并给出一个由具有这些字母的数字组成的电话号码(例如,我会得到639686237,因为n在6键上,e在3键上等)它也无法识别变量number和pnumber。
答案 0 :(得分:1)
您可以通过以下两种活动发送数据:
Intent intent = new Intent(CurrentActivity.this, MyService.class);
intent.putExtra("number", pnumber);
startActivity(intent);
您可以在MyService.class中获取此值:
Intent intent = getIntent();
String yourNumber = intent.getStringExtra("number");
或者您可以将您的值放在捆绑中:
在您当前的活动中:
Bundle bundle = new Bundle();
bundle.putString("number", pnumber);
bundle.putStirng("name", "yourNameValue");
bundle.putInt("age", "ageValue");
Intent intent = new Intent(CurrentActivity.this, MyService.class);
intent.putExtras(bundle);
startActivity(intent);
在您的MyService活动中:
Bundle bundle = getIntent().getExtras();
String number = bundle.getString("number");
String name = bundle.getString("name");
int age = bundle.getInt("age");
我希望能帮助你。
答案 1 :(得分:0)
由于第一个活动中的 intent.putExtra(String name,Bundle extra)语句,要在第二个活动中获取 pnumber ,我们需要字符串 name < / strong>即可。第二个类中没有数字(名称)和 pnumber 变量的范围。
因此,实例化第二类 ValueOfNumber 中具有数字值的变量,这将作为从意图中获取 pnumber 的关键。
使用
pnumber=extras.getString(ValueOfNumber); //ValueOfNumber is the value of number variable in first activity.
在Intent.putExtras之后调用startService。
请参阅This answer
答案 2 :(得分:-1)
使用的SharedPreferences。有一个很好的线程here。使用它,您可以将数字保存在首选项文件中(仅对当前应用程序可见,而不在文件系统中可见)。像这样:
private final String PREFS_NAME = "savefile";
private final String KEY_NUMBER = "num";
String strWithTheNumber = "00 123 456 789"
String strSavedValue = "";
SharedPreferences sharedPreferences = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
//将手机放入档案
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY_NUMBER, strWithTheNumber);
editor.commit();
//检索号码
strSavedValue = sharedPreferences.getString("num", null);