2012-01-13 84 views
0

我希望在我的应用程序的后台使用服务。当服务内部到达某个特定位置时,我希望将其停止并显示给用户通知,直到用户点击“确定”(某种警报窗口)才会消失。当他或她点击“确定” - >我希望一些在服务中达到的数据传递给我的活动。安卓服务和“警报窗口”

我可以请求帮助。我的服务已经运行良好,我希望使用警报对话框 - 但不知道如何从服务中调用它。

+0

锁定[AlertDialog](http://developer.android.com/reference/android/app/AlertDialog.html)以显示信息。 'Activity.sendBroadcast()'用于发送来自服务的信息和[BroadcastReceiver](http://developer.android.com/reference/android/content/BroadcastReceiver.html)用于在Activity中接收它。 – tidbeck 2012-01-13 00:38:53

回答

1

随着official documentation states后台服务不应该为了获得用户交互推出它自己的活动。 相反,您应该通知通知栏。通知可以被标记为坚持和振动,直到用户采取行动,这与在用户点击按钮之前不排除弹出窗口一样强大。按照上面的链接获得关于通知的良好(和官方)教程

如果您确实想要启动一个活动(并弹出一个对话框),您必须首先将以下标志设置为您的意图,否则您将得到一个异常。

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent); 
0

一旦你的服务中的某个点被启动,开始一个活动并且不使用setContent视图,但是只需在onCreate()中使用它来显示一个警告对话框。

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
builder.setMessage("ALERT") 
    .setCancelable(false) 
    .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int id) { 
      MyActivity.this.finish(); 
     } 
    }) 
    .setNegativeButton("No", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int id) { 
      dialog.cancel(); 
     } 
    }); 
AlertDialog alert = builder.create(); 

当用户按下okay时,对话框将关闭该活动。

编辑:

对于要发送到活动只是把它捆绑在开始活动的数据。

Intent intent = new Intent(this, SecondActivity.class); 
Bundle b = new Bundle(); 

// see Bundle.putInt, etc. 
// Bundle.putSerializable for full Objects (careful there) 

b.putXXXXX("key", ITEM); 
intent.putExtras(b); 
startActivity(intent); 

// -- later, in Activity 
Bundle b = this.getIntent().getExtras(); 
int i = b.getInt("key"); 
+0

或者你可以在ok按钮中调用dialog.cancle(),但是我会建议关闭整个活动。 – 2012-01-13 00:39:05

+0

但活动正在运行,服务正在后台运行,我希望以某种方式“更新”活动 - >将状态单选按钮更改为“检查”依赖于服务结果 – santBart 2012-01-13 00:41:50