英文:
How to return value from Android PhoneStateListener?
问题
我想获取当前用于数据传输的小区信息。在 Android Q 之前,我可以通过 [getallcellinfo()][1] 轻松获取它。然而,从 Android Q 开始,将通过 [onCellInfoChanged()][2] 来报告这些信息。
我不需要监听小区信息的变化,我只需要在调用方法的那一刻获取小区信息。我不能只是在 PhoneStateListener 内部返回 `((CellInfoLte) cellInfo).getCellIdentity().getEarfcn();`。如何实现这一点?
public int getEarfcn() {
telephonyManager.listen(new PhoneStateListener() {
@Override
public void onCellInfoChanged(List<CellInfo> cellInfoList) {
super.onCellInfoChanged(cellInfoList);
for (CellInfo cellInfo : cellInfoList) {
if (cellInfo instanceof CellInfoLte) {
int earfcn = ((CellInfoLte) cellInfo).getCellIdentity().getEarfcn();
// 在获取到 "earfcn" 后如何返回它?
}
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
return CellInfo.UNAVAILABLE;
}
[1]: https://developer.android.com/reference/kotlin/android/telephony/TelephonyManager?hl=en#getallcellinfo
[2]: https://developer.android.com/reference/kotlin/android/telephony/PhoneStateListener#oncellinfochanged
英文:
I want to get currently cell information in use for data transmit. Before Android Q, I can get it easily via getallcellinfo(). However, beginning with Android Q, this will be reported via onCellInfoChanged().
I don't need to listen on the changed of cell information, I just need the cell information at the moment that the method is called. I cannot just return ((CellInfoLte) cellInfo).getCellIdentity().getEarfcn();
inside PhoneStateListener. How to implement this?
public int getEarfcn() {
telephonyManager.listen(new PhoneStateListener() {
@Override
public void onCellInfoChanged(List<CellInfo> cellInfoList) {
super.onCellInfoChanged(cellInfoList);
for (CellInfo cellInfo : cellInfoList) {
if (cellInfo instanceof CellInfoLte) {
int earfcn = ((CellInfoLte) cellInfo).getCellIdentity().getEarfcn();
// How to return this "earfcn" once I get it?
}
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
return CellInfo.UNAVAILABLE;
}
答案1
得分: 0
无法使用 return。创建一个相同的接口
public void getEarfcn(ICellInfoChanged cellInfoChangedCallback) {
telephonyManager.listen(new PhoneStateListener() {
@Override
public void onCellInfoChanged(List<CellInfo> cellInfoList) {
super.onCellInfoChanged(cellInfoList);
for (CellInfo cellInfo : cellInfoList) {
if (cellInfo instanceof CellInfoLte) {
int earfcn = ((CellInfoLte) cellInfo).getCellIdentity().getEarfcn();
cellInfoChangedCallback.onCallback(cellInfo);
}
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}
英文:
You can't use return. Create an interface same
public voi getEarfcn(ICellInfoChanged cellInfoChangedCallback) {
telephonyManager.listen(new PhoneStateListener() {
@Override
public void onCellInfoChanged(List<CellInfo> cellInfoList) {
super.onCellInfoChanged(cellInfoList);
for (CellInfo cellInfo : cellInfoList) {
if (cellInfo instanceof CellInfoLte) {
int earfcn = ((CellInfoLte) cellInfo).getCellIdentity().getEarfcn();
cellInfoChangedCallback.onCallback(cellInfo);
}
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论