我正在使用附近的连接来创建设备之间的连接。建立连接后,将更改活动。现在,如果设备断开连接,则将调用回调,但在旧活动中会收到该回调。现在,我想显示一个AlertDialog,但是该对话框从未显示,因为它显示在旧活动上。如何显示有关新活动的对话框?
我正在使用附近的连接,例如:URL
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();
}
对话框应显示在当前活动上
答案 0 :(得分:0)
在活动中写一个方法为:
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);
}
}
答案 1 :(得分:0)
使用事件总线实现或使用sendBroadcast()
发送回调,并让每个Activity
在BroadcastReceiver
中注册一个onResume()
,然后在onPause()
中取消注册。 / p>