android撥號實現
說到安卓,實現肯定是先談界面,先前在網上看到一個關於撥號器的實現視頻教程,很簡單,直說重點:由於系統已經實現了電話撥號功能,所以我們只需要調用這個功能就可以了。
界面:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.bohaoqi.MainActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/alert" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tel"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button"
/>
</LinearLayout>
//爲了支持國際化建議將中文字段放入String.xml裏面
<resources>
<string name="app_name">bohaoqi</string>
<string name="hello">hello world</string>
<string name="mobie">用戶名</string>
<string name="alert">請輸入號碼</string>
<string name="button">撥號</string>
</resources>
只是demo,首選線性佈局。
實現步驟:
1.寫邏輯事件
package com.example.administrator.bohaoqi;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//get the telphone number View
EditText tel = (EditText) findViewById(R.id.tel);
//get the phone number
String num = tel.getText().toString().trim();
if(TextUtils.isEmpty(num)){
//如果號碼爲空
Toast.makeText(MainActivity.this,"The phone number can not be empty!",Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
+ num));
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED)
{
return;
}
startActivity(intent);
}
}
});
}
}
2.配置權限
<uses-permission android:name="android.permission.CALL_PHONE" />
撥打電話 android.permission.CALL_PHONE,允許程序從非系統撥號器裏輸入電話號碼
通話權限 android.permission.CALL_PRIVILEGED,允許程序撥打電話,替換系統的撥號器界面(這個不用寫上去,要系統軟件)才過得了。
4.實際上運行時很可能會出現call not send 報錯
別慌,先看看你是不是配了權限,在看看你的電話是不是處於掛起狀態。最後試試看是不是你的API的不同,高級一些的版本可能已經不支持這種方式了。