Java 如何在mainactivity中定义广播接收器类和phonestatechange类?

Java 如何在mainactivity中定义广播接收器类和phonestatechange类?,java,android,Java,Android,这是我的phonestate类,我在其中检查电话状态更改 public class CustomPhoneStateListener extends PhoneStateListener { private static final String TAG = "CustomPhoneStateListener"; public void onCallStateChange(int state, String incomingNumber){ Log.v(TAG, "WE A

这是我的phonestate类,我在其中检查电话状态更改

public class CustomPhoneStateListener extends PhoneStateListener {

private static final String TAG = "CustomPhoneStateListener";

public void onCallStateChange(int state, String incomingNumber){

        Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
        Log.v(TAG, incomingNumber);

        switch(state){
                case TelephonyManager.CALL_STATE_RINGING:
                        Log.d(TAG, "RINGING");
                        break;
        }        }
这是我的广播接收器类,用于连接广播

    public class CustomBroadcastReceiver extends BroadcastReceiver {

private static final String TAG = "CustomBroadcastReceiver";

@Override
public void onReceive(Context context, Intent intent) {
        Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
    TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();

    telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);


    Bundle bundle = intent.getExtras();
    String phoneNr= bundle.getString("incoming_number");
        Log.v(TAG, "phoneNr: "+phoneNr);
}

如何在主活动中定义它?

将其包含在您的android清单中

<uses-permission android name="android.permission.READ_PHONE_STATE" />

请参阅。

将其放在您的活动中,如:

private CustomBroadcastReceiver receiver = new CustomBroadcastReceiver();
然后添加到OnCreate()中


但将TelephonyManager放在BroadcastReceiver中毫无意义。您可以将其添加到活动中,如上面的答案所示。

您是否尝试在MainActivity中声明这些类…它在活动中也起作用..无论您在何处声明了类和侦听器,唯一重要的是从何处注册接收者..就这样。希望它能有所帮助。谢谢。。。另一个查询,我使用“Log.v(TAG,“phoneNr:+phoneNr)”;“这将在logcat中打印电话号码,,,但我需要在设备中显示此号码作为弹出窗口,同时响铃…..如此视频。。。。您可以使用这样的toast消息来显示它。。。。Toast.makeText(上下文,phoneNumber+“Calling..”,Toast.LENGTH_LONG.show();希望能有所帮助。谢谢你的回答。。。。另一个查询,我使用“Log.v(TAG,“phoneNr:+phoneNr)”;“这将在logcat中打印电话号码,,,但我需要在设备中显示此号码作为弹出窗口,同时响铃…..如此视频。。。。使用Toast.makeText(YourActivity.this,“接收来自”+phoneNr,Toast.LENGTH_SHORT.show)的呼叫);在CALL_STATE_RINGINGI之前尝试过这个方法,,,这显示了错误“Toast类型中的方法makeText(Context,CharSequence,int)不适用于参数(CustomPhoneStateListener,String,int)”您使用了YourActivity。这个?我使用了那个,现在没有错误,,,但是Toast不会出现..我没有使用任何活动(前端)在这个项目中..在呼叫屏幕中我需要打印..日志cat错误是。。。“10-24 09:05:18.041:I/ActivityManager(293):从pid-1启动u0{act=android.intent.action.MAIN flg=0x10840000 cmp=com.android.phone/.InCallScreen}”
private CustomBroadcastReceiver receiver = new CustomBroadcastReceiver();
registerReceiver(receiver, new IntentFilter(YPUR_ACTION));