安卓专题

在安卓中编程拨打电话案例源码

  尽管安卓内建了手工电话呼叫功能,但是在一些场合我们还是需要在应用程序中进行电话呼叫,这很容易通过Intent来实现,为了监视电话设备状态,配合使用PhoneStateListener和 TelephonyManager 类。

activity_main.xml:

<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"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/phoneNumber"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:hint="Type a number to call..."
        android:ems="10"
        android:inputType="phone" />

    <Button
        android:id="@+id/call"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/phoneNumber"
        android:layout_marginTop="20dp"
        android:text="Call" />
   
     <Button
        android:id="@+id/dial"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/call"
        android:layout_marginTop="20dp"
        android:text="Dial and Call" />

</RelativeLayout>

拨打电话核心代码是:

String uri = "tel:"+number.getText().toString();
Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(uri));

ACTION_DIAL是拨打电话功能,URI是电话号码。

‘下面是让电话输入电话号码,然后进行拨打的主活动代码:

public class MainActivity extends Activity {

       private Button callBtn;
       private Button dialBtn;
       private EditText number;
      
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              number = (EditText) findViewById(R.id.phoneNumber);
              callBtn = (Button) findViewById(R.id.call);
              dialBtn = (Button) findViewById(R.id.dial);

              // add PhoneStateListener for monitoring
              MyPhoneListener phoneListener = new MyPhoneListener();
              TelephonyManager telephonyManager =
                     (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
              // receive notifications of telephony state changes
              telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
                           
              callBtn.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View v) {
                            try {
                                   // set the data
                                   String uri = "tel:"+number.getText().toString();
                                   Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                                  
                                   startActivity(callIntent);
                            }catch(Exception e) {
                                   Toast.makeText(getApplicationContext(),"Your call has failed...",
                                          Toast.LENGTH_LONG).show();
                                   e.printStackTrace();
                            }
                     }
              });
             
              dialBtn.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View v) {
                            try {
                                   String uri = "tel:"+number.getText().toString();
                                   Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(uri));
                                  
                                   startActivity(dialIntent);
                            }catch(Exception e) {
                                   Toast.makeText(getApplicationContext(),"Your call has failed...",
                                          Toast.LENGTH_LONG).show();
                                   e.printStackTrace();
                            }
                     }
              });
       }
      
       private class MyPhoneListener extends PhoneStateListener {
               
              private boolean onCall = false;
 
              @Override
              public void onCallStateChanged(int state, String incomingNumber) {
 
                     switch (state) {
                     case TelephonyManager.CALL_STATE_RINGING:
                            // phone ringing...
                            Toast.makeText(MainActivity.this, incomingNumber + " calls you",
                                          Toast.LENGTH_LONG).show();
                            break;
                    
                     case TelephonyManager.CALL_STATE_OFFHOOK:
                            // one call exists that is dialing, active, or on hold
                            Toast.makeText(MainActivity.this, "on call...",
                                          Toast.LENGTH_LONG).show();
                            //because user answers the incoming call
                            onCall = true;
                            break;

                     case TelephonyManager.CALL_STATE_IDLE:
                            // in initialization of the class and at the end of phone call
                           
                            // detect flag from CALL_STATE_OFFHOOK
                            if (onCall == true) {
                                   Toast.makeText(MainActivity.this, "restart app after call",
                                                 Toast.LENGTH_LONG).show();
 
                                   // restart our application
                                   Intent restart = getBaseContext().getPackageManager().
                                          getLaunchIntentForPackage(getBaseContext().getPackageName());
                                   restart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                   startActivity(restart);
 
                                   onCall = false;
                            }
                            break;
                     default:
                            break;
                     }
                    
              }
       }

}

在PhoneStateListener中设置权限READ_PHONE_STATE 完成电话呼叫的监视权限:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jdon.android.phonecalltest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="19" />
   
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.jdon.android.phonecalltest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


 

本案例源码下载