Android拨打电话实例

时间:2022-11-10 00:26:26

很多小例子由于一段时间不接触,突然就忘了是怎么实现了的,就贴出来,以备查用吧。

Android拨打电话,主要的代码就是一句

Intent phoneIntent = new Intent("android.intent.action.CALL",Uri.parse("tel:" + inputStr));
startActivity(phoneIntent);

当然,还要记得在manifest 添加权限

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

1.效果图:

Android拨打电话实例


2.界面布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
tools:context=".MainActivity" >

<EditText
android:id="@+id/number"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="请输入电话号码"
android:phoneNumber="true" />
<Button
android:id="@+id/send"
android:layout_below="@+id/number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="拨 打"

/>

</RelativeLayout>

3.程序代码

package com.example.phonecalldemo;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
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 numberText;
private Button sendButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberText = (EditText) findViewById(R.id.number);
sendButton = (Button) findViewById(R.id.send);
sendButton.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send:
// 取得输入的电话号码串
String inputStr = numberText.getText().toString();

if (inputStr == null) {
Toast.makeText(getApplication(), "请输入电话号码", 5).show();
return;
}

if (inputStr.length() != 8 && inputStr.length() != 11) {
Toast.makeText(getApplication(), "号码位数不对", 5).show();
numberText.setText("");
return;
}

Intent phoneIntent = new Intent("android.intent.action.CALL",Uri.parse("tel:" + inputStr));
startActivity(phoneIntent);

break;

default:
break;
}

}

}