gpt4 book ai didi

java - android - 返回类实例中更改的数据

转载 作者:太空宇宙 更新时间:2023-11-04 12:46:06 25 4
gpt4 key购买 nike

目标是拥有一个名为 CallReceiver 的类,它实现 BroadcastReceiver该类正在监听调用,当有调用时,它会将调用者号码返回到创建实例的 Activity 。

示例:

主要 Activity :

CallReciver callreciver = new CallReciver(getApplicationContext());

CallReciver.java

public class CallReceiver extends BroadcastReceiver {

private Context mContext;

CallReceiver(Context context) {
this.mContext = context;
}

@Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

Intent i = new Intent(mContext, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("callMsg", incomingNumber);

mContext.startActivity(i);
}
}

我尝试在检测到调用时发送带有号码的 Intent ,但问题是该 Intent 启动 Activity 并初始化变量,我只需要获取号码。

要求的结果:CallReceiver 将号码发送到 MainActivity

最佳答案

编辑答案,因为您的要求一开始并不明确。如果您只想要此接收器中的调用者号码,您可能想尝试此 fragment 。从这个答案得到这个想法 How to get phone number from an incoming call?

在您的 list 中:

<receiver android:name=".ServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>

在您的接收器中:

public class ServiceReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener(){
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
Intent i = new Intent(mContext, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("callMsg", incomingNumber);
mContext.startActivity(i);
}
},PhoneStateListener.LISTEN_CALL_STATE);
}

关于java - android - 返回类实例中更改的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36308126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com