我需要一个弹出式对话框在我从不同的线程接收到消息时显示出来,但是该对话框不应依赖于Activity,即它应该在屏幕焦点所在的任何地方显示。
这可以实现吗?因为对话框是按Activity处理的,所以我考虑使用一个服务,但又会增加一个线程,而我想避免这种情况。
还有其他选项可供选择吗?
这可以实现吗?因为对话框是按Activity处理的,所以我考虑使用一个服务,但又会增加一个线程,而我想避免这种情况。
还有其他选项可供选择吗?
创建通知的指南在这里:http://developer.android.com/guide/topics/ui/notifiers/notifications.html。使用通知系统——不要使用对话框代替通知
如果您的后台服务需要通知用户,请使用标准通知系统——不要使用对话框或toast通知用户。对话框或toast会立即接管焦点并打断用户,将焦点从他们正在做的事情上转移走:当对话框出现时,用户可能正在输入文本,并且可能会意外地对对话框采取行动。用户习惯于处理通知,并可以在方便的时候下拉通知栏以回复您的消息。
public abstract class BaseActivity extends Activity{
protected static BaseActivity current_context = null;
@override
protected void onPause(){
current_context = null;
super.onPause();
}
@override
protected void onResume(){
current_context = this;
super.onResume();
}
public static void showDialog(/*your parameters*/){
//show nothing, if no activity has focus
if(current_context == null)return;
current_context.runOnUiThread(new Runnable() {
@override
public void run(){
AlertDialog.Builder builder =
new AlertDialog.Builder(current_context);
//your dialog initialization
builder.show();
}
});
}
}
在您的线程中展示您与BaseActivity.showDialog(..)
的对话。但是,如果您想在目标设备的任何活动上方展示您的对话框,则此方法不起作用。
替代方案:
AlertDialog dialog;
//add this to your code
dialog = builder.create();
Window window = dialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mInputView.getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//end addons
alert.show();
lp.token = mInputView.getWindowToken();
我们需要一个视图来获取token吗?如果是,我们需要一个活动上下文! - C--