我试图在我的应用程序中监听传入调用,因此我为此创建了一个广播接收器,但是当我在 toast 中传递上下文时它显示错误。谁能弄清楚我做错了什么? 这是我的代码:
public class MainActivity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tmngr= (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
MyPhoneStateListener PhoneListener = new MyPhoneStateListener();
tmngr.listen(PhoneListener,PhoneStateListener.LISTEN_CALL_STATE);
}
private class MyPhoneStateListener extends PhoneStateListener {
public void onCallStateChanged(int state,String incoming)
{
if (state == 1) {
String msg = "New Phone Call Event. Incomming Number : "+incoming;
int duration = Toast.LENGTH_LONG;
//i am getting error here( context )
Toast toast = Toast.makeText(context, msg, duration);
toast.show();
}
}}}
最佳答案
这是我所做的(非常感谢@egor),尽管我花了一些时间才理解。这是代码:
public class MainActivity extends BroadcastReceiver {
Context pcontext;
@Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tmngr= (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
//referencing the context
pcontext=context;
//passing it to phonelistener
MyPhoneStateListener PhoneListener = new
MyPhoneStateListener(pcontext);
tmngr.listen(PhoneListener,PhoneStateListener.LISTEN_CALL_STATE);
}
private class MyPhoneStateListener extends PhoneStateListener {
public MyPhoneStateListener(Context pcontext) {
}
public void onCallStateChanged(int state,String incoming)
{
if (state == 1) {
String msg = "New Phone Call Event. Incomming Number : "+incoming;
int duration = Toast.LENGTH_LONG;
// Context pcontext;
Toast toast;
toast = Toast.makeText(pcontext, msg, duration);
toast.show();
}
}
}
}
关于android - 广播接收器android中的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29440487/