android.content.res.resource android .content.context.getresource()在null对象引用上

时间:2015-07-28 12:51:30

标签: android broadcastreceiver

我正在开发一个呼叫阻止应用程序,但我遇到了这个错误。 错误附后。 你能帮帮我吗?

public class IncomingCall extends BroadcastReceiver {
Context context;
@Override
public void onReceive(Context context, Intent intent) {
    try {
        // TELEPHONY MANAGER class object to register one listner
        TelephonyManager tmgr = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        //Create Listner
        MyPhoneStateListener PhoneListener = new MyPhoneStateListener();
        // Register listener for LISTEN_CALL_STATE
        tmgr.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
    } catch (Exception e) {
        Log.e("Phone  Receive Error", " " + e);
    }
}
    private class MyPhoneStateListener extends PhoneStateListener {
        public void onCallStateChanged(int state, String incomingNumber) {
             Log.d("MyPhoneListener",state+"   incoming no:"+incomingNumber);
            // state = 1 means when phone is ringing
            if (state == 1) {
                String msg = " New Phone Call Event. Incomming Number : "+incomingNumber;
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText( context, msg,duration);
                toast.show();
            }
        }
    }
}

Error

1 个答案:

答案 0 :(得分:1)

您遇到此错误是因为" context" in" Toast.makeText(context,msg,duration);"一片空白。您需要设置班级"上下文" onReceive方法中的字段:

@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;