0

我正在尝试创建一个应用程序,该应用程序将在收到呼叫时执行不同的功能。为了做一个小的工作示例,我已经扩展了我的课程BroadcastReceiver,并尝试让 toast 通知显示出来。

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class IncomingCallInterceptor extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Do something.", Toast.LENGTH_LONG).show();
    }
}

我在我的AndroidManifest.xml文件中添加了这个权限:

<application android:icon="@drawable/icon" android:label="Incoming Call Interceptor">
    <receiver android:name="IncomingCallInterceptor">
        <intent-filter>
             <action android:name="android.intent.action.PHONE_STATE"/>
        </intent-filter>
    </receiver>
</application>

我的测试设备运行的是 Android 4.4.2。当有人打来电话时,不会出现 Toast 通知。

4

2 回答 2

0

试试这个代码Monitor the state of the Phone

import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class PhoneReceiver extends PhoneStateListener {
Context context;
public PhoneReceiver(Context context) {
this.context = context;
}
@Override
public void onCallStateChanged(int state, 
String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
Toast.makeText(context, "onCallStateChanged state=" + 
state + "incomingNumber=" + incomingNumber, 
Toast.LENGTH_LONG).show(); 
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Toast.makeText(context, "idle", 
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_RINGING:
Toast.makeText(context, "ringing", 
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Toast.makeText(context, "offhook", 
Toast.LENGTH_LONG).show();
break;
}
}
}
于 2014-04-12T20:24:07.340 回答
0

从类似的线程中找到答案:Incoming call broadcast receiver not working (Android 4.1)

从 Android 3.0 开始,您必须在广播接收器开始工作之前从您的应用程序手动启动一个活动。

于 2014-04-13T00:23:39.080 回答