如何在活动更改后获取当前活动



我正在使用附近的连接在设备之间创建连接。建立连接后,活动将更改。现在,如果设备断开连接,则会调用回调,但在旧活动中收到回调。现在我想显示一个 AlertDialog,但该对话框永远不会显示,因为它显示在旧活动上。如何显示新活动的对话框?

我正在使用附近的连接,如下所示:网址

private Activity mActivity;
public RemoteConnection(Activity activity){
    mActivity = activity;
} 
  // For simplicity I did only include this method
  @Override
  public void onDisconnected(String endpointId) {
    // We've been disconnected from this endpoint. No more data can be
    // sent or received.
    new AlertDialog.Builder(mActivity)
      .setTitle("Disconnection")
      .setMessage("Other device is disconnected")
      .setIcon(android.R.drawable.ic_dialog_alert)
      .show();
  }

对话框应显示在当前活动上

在活动中编写方法如下:

public void showAlert(activity)
{
    new AlertDialog.Builder(activity)
  .setTitle("Disconnection")
  .setMessage("Other device is disconnected")
  .setIcon(android.R.drawable.ic_dialog_alert)
  .show();
}

并更改以下代码:

@Override
 public void onDisconnected(String endpointId) {
// We've been disconnected from this endpoint. No more data can be
// sent or received.
new AlertDialog.Builder(mActivity)
  .setTitle("Disconnection")
  .setMessage("Other device is disconnected")
  .setIcon(android.R.drawable.ic_dialog_alert)
  .show();

}

自:

@Override
 public void onDisconnected(String endpointId) {
// We've been disconnected from this endpoint. No more data can be
// sent or received.
if(((YourActivityA)activity) != null)
{
    ((YourActivityA)activity).showAlert(activity);
}
else if(((YourActivityB)activity) != null)
{
    ((YourActivityB)activity).showAlert(activity);
}
}

使用事件总线实现或使用 sendBroadcast() 发送回调,并让每个ActivityonResume() 中注册一个BroadcastReceiver,并在 onPause() 中取消注册。

相关内容

  • 没有找到相关文章

最新更新