在Android模拟器中开发时,有时需要模拟拨打电话功能,由于模拟器不能直接当做真机使用,所以我们需要再模拟器中模拟真机拨打电话,首先需要创建两个模拟器,当做两部Android手机来使用。由于Android系统中已经有了拨打电话的Activity,因此我们只需要编写代码调用即可。具体如下:
1. 建立如下布局:
对应的布局文件xml:
1
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent" >
5
6
8 android:layout_width="wrap_content"
9 android:layout_height="wrap_content"
10 android:text="@string/phone_tl"
11 tools:context=".MainActivity" />
12
13
15 android:layout_width="fill_parent"
16 android:layout_height="wrap_content"
17 android:layout_alignParentLeft="true"
18 android:layout_below="@+id/textView1"
19 android:layout_marginTop="14dp"
20 android:ems="10" >
21
22
23
24
25
27 android:layout_height="wrap_content"
28 android:layout_alignParentLeft="true"
29 android:layout_below="@+id/editText1"
30 android:id="@+id/btn_call"
31 android:text="@string/button" />
32
33
2. 编写代码文件:
1 packagecom.example.phone;2
3 importandroid.net.Uri;4 importandroid.os.Bundle;5 importandroid.app.Activity;6 importandroid.content.Intent;7 importandroid.view.Menu;8 importandroid.view.View;9 importandroid.widget.Button;10 importandroid.widget.EditText;11
12 /**
13 *@authorfanchangfa14 * 拨打电话模拟15 */
16 public class MainActivity extendsActivity {17
18 private EditText phone_text; //获取用于输入电话号码的文本框对象
19 private Button btn_call; //获取拨打电话的Button对象
20 @Override21 public voidonCreate(Bundle savedInstanceState) {22 super.onCreate(savedInstanceState);23 setContentView(R.layout.activity_main);24
25 /*
26 * 初始化控件27 **/
28 phone_text = (EditText) this.findViewById(R.id.editText1);29
30 btn_call = (Button) this.findViewById(R.id.btn_call);31
32 btn_call.setOnClickListener(newbtn_listener());33 }34
35 //拨打电话的按钮单击事件:
36 private final class btn_listener implementsView.OnClickListener{37 public voidonClick(View v)38 {39 String phone =phone_text.getText().toString();40
41 Intent Int_call = newIntent();42
43 Int_call.setAction("android.intent.action.CALL");44 Int_call.setData(Uri.parse("tel:"+phone));45
46 //使用Intent时,还需要设置其category,不过47 //方法内部会自动为Intent添加类别:android.intent.category.DEFAULT
48
49 startActivity(Int_call);50 }51 }52
53 @Override54 public booleanonCreateOptionsMenu(Menu menu) {55 getMenuInflater().inflate(R.menu.activity_main, menu);56 return true;57 }58 }
3. 主要任务完成了,不过此时还不能顺利的实现功能,谷歌为了保护用户的私人信息设置了一些权限,我们开发的时候需要将特定的权限加入才能正常使用,再此我们需要将拨打电话的权限加入到AndroidMainfest.xml文件中:
1
2
4. 此时运行程序,不过需要两个模拟器来实现。启动两个模拟器:
可以看到,我们所编写的程序是部署在5556这个模拟器上,另外一个模拟器是5554,现在在我们的程序中输入5554点击拨打按钮,会自动调用系统的拨打电话Activity,效果如下:
这个功能通常是在程序中需要调用拨打电话程序时使用,例如在开发查看人员信息时,如果有电话号码可以直接调用此系统的此Activity进行拨打电话。