在 PhoneStateListener 監聽來電狀態變化時,嘗試在通話結束(CALL_STATE_IDLE)啟動某個 Activity,但編譯報錯:The constructor Intent(MyPhoneStateListener, Class) is undefined。
public class MyPhoneStateListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
switch(state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d("DEBUG", "IDLE");
Intent missintent = new Intent(this, MissedCall.class); // 錯誤:this 指向 Listener
startActivity(missintent); // 錯誤:Listener 無 startActivity 方法
break;
// ... 其他狀態
}
}
}
PhoneStateListener 不是 Context 子類,無法直接作為 Intent 建構子的第一個參數PhoneStateListener 沒有 startActivity() 方法Context(通常是 Activity 或 Service)來啟動元件public class MyPhoneStateListener extends PhoneStateListener {
private Context mContext;
public MyPhoneStateListener(Context context) {
mContext = context;
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch(state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d("DEBUG", "IDLE");
Intent intent = new Intent(mContext, MissedCall.class);
// 從非 Activity 啟動 Activity 需加此旗標
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
break;
// ...
}
}
}
public class CallMonitorService extends Service {
private TelephonyManager telephonyManager;
private MyPhoneStateListener listener;
@Override
public void onCreate() {
super.onCreate();
listener = new MyPhoneStateListener(this); // 傳入 Service 本身作為 Context
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
// ... onBind, onDestroy 等
}
在 AndroidManifest.xml 宣告:
<receiver android:name=".CallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
接收器實作:
public class CallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
Intent launchIntent = new Intent(context, MissedCall.class);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(launchIntent);
}
}
}
android.util.AndroidRuntimeException<uses-permission android:name="android.permission.READ_PHONE_STATE" />onDestroy() 取消監聽:telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE)PhoneStateListener 本身無法直接啟動 Activity,必須持有有效的 Context 並加上 FLAG_ACTIVITY_NEW_TASK。根據使用場景選擇在 Activity、Service 或 BroadcastReceiver 中實作,並注意版本相容性與權限管理。