收到电话时做某事

时间:2014-04-12 20:10:48

标签: android broadcastreceiver android-toast

我正在尝试创建一个在收到呼叫时执行不同功能的应用程序。为了做一个小的工作示例,我已经让我的课程扩展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。当有人打电话时,没有任何吐司通知出现。

2 个答案:

答案 0 :(得分: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;
}
}
}

答案 1 :(得分:0)

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

  

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