Android 电话状态监听

来源:互联网 发布:java里poi是什么 编辑:程序博客网 时间:2024/05/16 08:38

   今天介绍一下Android电话状态的监听。监听Android电话状态需要用到PhoneStateListener。下面通过一个具体的实例来看看具体怎么实现的。

配置文件:

<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.pan.phonecalldemo.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>
布局文件:

<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: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=".MainActivity" >    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:text="Call:130 6681 9390" /></RelativeLayout>
代码:

public class MainActivity extends Activity {private ListenToPhoneState listener;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.button1).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {call();}});}private void call() {try {Intent callIntent = new Intent(Intent.ACTION_CALL);callIntent.setData(Uri.parse("tel:13723740766"));startActivity(callIntent);TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);listener = new ListenToPhoneState();tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);} catch (ActivityNotFoundException activityException) {Log.e("telephony-example", "Call failed", activityException);}}private class ListenToPhoneState extends PhoneStateListener {public void onCallStateChanged(int state, String incomingNumber) {Log.i("telephony-example", "State changed: " + stateName(state));}String stateName(int state) {switch (state) {case TelephonyManager.CALL_STATE_IDLE:return "Idle";case TelephonyManager.CALL_STATE_OFFHOOK:return "Off hook";case TelephonyManager.CALL_STATE_RINGING:return "Ringing";}return Integer.toString(state);}}}



0 0
原创粉丝点击