我有以下代码,基本上我每 10 秒从 Web 服务获取数据,并在警报对话框和通知上显示每次获取的内容。问题是,如果警报尚未从上一个周期关闭并且仍在页面上,那么如何不弹出警报,这样用户必须关闭的同时不会打开 2 个或更多相同的警报。
public class myActivity extends Activity {
public class getActiveAlerts extends Thread {
public void run() {
while (true)
{
try {
.... code to get data from web service .....
似乎即使 AlertDialog 存在并且未受影响,当接下来的 10 秒到来时,即使旧警报仍然存在,“alert.isShowing”仍然显示 false,并且它会创建一个具有相同内容的新警报每 10 秒更新一次属性。 (我本以为如果打开警报,alert.isShowing 会显示 true 并且不会创建新警报。我在这里做错了什么还是有更好的方法?
最后,我不相信有一种方法可以检测通知当前是否处于 Activity/显示状态并且尚未单击关闭。当线程在 10 秒后被调用重新启动时,是否有一种标准方法来检查通知是否“正在显示”,这样通知就不会每 10 秒创建一次?
String root = doc.getDocumentElement().getNodeName();
//lets set alert title and msg to whatever "root" is for now, root contains the data I get from my web service.
myActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder alertBuild = new AlertDialog.Builder(myActivity.this);
alertBuild.setMessage(root)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = alertBuild.create();
if(alert.isShowing())
{
Log.v("alert", "isShowing==true");
}
else {
Log.v("alert", "isShowing==false");
alert.setTitle(root);
alert.setIcon(R.drawable.ic_launcher);
alert.show();
}
}
});
displayNotification(root, root);
}
}
}
}catch (SAXParseException err) {
Log.v(" " , err.getMessage ());
}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
}catch (Throwable t) {
t.printStackTrace ();
}
try {
Thread.sleep(10000); // sleeps for 10 seconds then runs myActivity again
} catch (InterruptedException e) {
e.printStackTrace();
}
}// close while loop
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getActiveAlerts thread = new getActiveAlerts();
thread.start();
}
public void displayNotification(String msg, String desMsg)
{
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, msg + "\n" + desMsg, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 1, new Intent(this, myActivity.class), 0);
notification.setLatestEventInfo(this, "new alert", "", contentIntent);
manager.notify(1, notification);
}
最佳答案
您每次都在创建一个全新的 AlertDialog 对象。由于您刚刚创建了它,并且尚未对该特定对象调用 show,因此该特定对象的 isShowing 为 false。任何先前创建的对话框可能会显示,也可能不会显示,但您不会询问这些对象。
您可以通过在可运行对象中调用 Activity 的方法来解决此问题,无论您想要发布什么结果,而不是在可运行对象中进行发布。这将使 Activity 跟踪当前显示的对话框,并且如果对话框已经可见,则不会创建新对话框。
请注意,如果您的线程的生命周期比您的 Activity 的生命周期长,那么在后台线程中引用您的 Activity 可能会导致巨大的内存泄漏。考虑在线程中存储对监听器的弱引用,而不是对 Activity 的硬引用。
关于Android 警报对话框 isShowing 属性始终为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9541061/