android调用状态示例

【android调用状态示例】我们还可以使用TelephonyManager类获取呼叫状态信息。为此,我们需要通过传递PhonStateListener实例来调用TelephonyManager类的listen方法。
必须实现PhoneStateListener接口以获取呼叫状态。它提供一种方法onCallStateChanged()。
Android通话状态示例
让我们看一个示例,在此示例中,我们确定电话是在响铃还是在通话中,或者电话既不在响铃也不在通话中。
activity_main.xml在此示例中,此文件中没有任何组件。
活动类让我们编写代码以了解调用状态。

package com.srcmini.callstates; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.view.Menu; import android.widget.Toast; public class MainActivity extends Activity {@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); PhoneStateListener callStateListener = new PhoneStateListener() { public void onCallStateChanged(int state, String incomingNumber) { if(state==TelephonyManager.CALL_STATE_RINGING){ Toast.makeText(getApplicationContext(), "Phone Is Riging", Toast.LENGTH_LONG).show(); } if(state==TelephonyManager.CALL_STATE_OFFHOOK){ Toast.makeText(getApplicationContext(), "Phone is Currently in A call", Toast.LENGTH_LONG).show(); }if(state==TelephonyManager.CALL_STATE_IDLE){ Toast.makeText(getApplicationContext(), "phone is neither ringing nor in a call", Toast.LENGTH_LONG).show(); } } }; telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE); }@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; }}

AndroidManifest.xml你需要在AndroidManifest.xml文件中提供READ_PHONE_STATE权限。
< ?xml version="1.0" encoding="utf-8"?> < manifest xmlns:androclass="http://schemas.android.com/apk/res/android" package="com.srcmini.callstates" android:versionCode="1" android:versionName="1.0" >< uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> < 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.srcmini.callstates.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>

输出:
android调用状态示例

文章图片
android调用状态示例

文章图片

    推荐阅读