gpt4 book ai didi

java - 结束 BroadcastReceiver 中的 Android Activity ?

转载 作者:行者123 更新时间:2023-12-01 23:19:56 26 4
gpt4 key购买 nike

当我收到电话铃声广播时,我正在启动一项 Activity ,但是一旦接听或中止调用,该 Activity 就不会结束(或关闭)。我需要在 else if 中结束 Activity ,但不确定如何处理?最好的方法是什么?

public class CallReceiver extends BroadcastReceiver {
Intent i;

@Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
assert state != null;
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
i = new Intent(context, IncomingCall.class);
i.putExtras(intent);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
context.startActivity(i);
}
else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
// WHAT GOES HERE?
}
}
}

最佳答案

您可以使用LocalBroadcast Manager用于从 onReceive 内的 else 语句发送本地广播消息。在 Activity (您想要关闭)中,您可以注册接收器以接收本地广播。每当调用 else 部分时,您都可以发送本地广播,该广播将由您的 Activity 接收。然后在您的 Activity 中您可以调用finish()

对于 LocalBroadcastManager,文档说:

It is a helper to register for and send broadcasts of Intents to local objects within your process. This is has a number of advantages over sending global broadcasts with sendBroadcast(Intent). One of them is that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.`

此广播仅适用于您的应用程序。所以也很安全。您可以在此处查看如何使用它:how to use LocalBroadcastManager? 。希望对您有帮助。

关于java - 结束 BroadcastReceiver 中的 Android Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20751904/

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