2. 由於我們需取得目前手機的通話狀態,因此必需在AndroidManifest.xml內新增一個讀取通話狀態的權限。
3. MainActivity.java
package org.me.android_callstate;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
//電話狀態的Listener
MyPhoneStateListener myPhoneStateListener = new MyPhoneStateListener();
//取得TelephonyManager
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//將電話狀態的Listener加到取得TelephonyManager
telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
public class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String phoneNumber) {
switch (state) {
//電話狀態是閒置的
case TelephonyManager.CALL_STATE_IDLE:
break;
//電話狀態是接起的
case TelephonyManager.CALL_STATE_OFFHOOK:
Toast.makeText(MainActivity.this, "正接起電話…", Toast.LENGTH_LONG).show();
break;
//電話狀態是響起的
case TelephonyManager.CALL_STATE_RINGING:
Toast.makeText(MainActivity.this, phoneNumber + "正打電話來…", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
}
4. AndroidManifest.xml
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.me.android_callstate">
<application>
<activity android:name=".MainActivity" android:label="MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
</manifest>4. 執行之後的畫面。







您好!我今天試玩了一下這個程式
回覆刪除發現打開之後Toast完全沒有反應...