在安卓中从服务弹出警示对话框

4

我想要建立一个活动感知的应用程序。 我使用了来自Android开发者的活动识别示例作为起点。 在这个示例中,用户开始移动时,会出现一个通知,要求打开GPS。 我想要用一个闹钟对话框和一些声音来替换这个通知。 我找到的最简单和最常见的警报框对我来说不起作用,因为它是不可能从服务中创建提醒。 感谢Harsh给了我一种活动的想法。 代码工作的那一刻我将发布代码。 提前谢谢您。 按照承诺,从服务调用的警报框的工作代码: 1)服务文件中的代码:

    Intent intent;
    intent = new Intent(this, MyAlert.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

2) 提示活动(alert activity)的.java文件中的代码:

    public class MyAlert extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_alert);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

    // set title
    alertDialogBuilder.setTitle("Your Title");

    // set dialog message
    alertDialogBuilder
            .setMessage("Your Message")
            .setCancelable(false)
            .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    stopService(getIntent());
                    dialog.cancel();
                    finish();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

3) 警告活动清单中没有代码,只有布局 4) manifest.xml:

    <activity
        android:name="com.igor.map.MyAlert"
        android:theme="@android:style/Theme.Dialog">
    </activity>

所有的工作都已经完成,但还有一个问题,当我点击“确定”按钮时,警告框关闭了,但应用程序的标签仍然存在,直到我点击屏幕为止。


你说的“不工作”是什么意思? - Rohan Kandwal
可能重复 => http://stackoverflow.com/questions/6924900/how-to-display-alert-diaologpopup-from-backgroung-running-service - Harsh Goswami
你不能在服务中使用构建器。 - Ig0r82
1个回答

5

从服务启动活动,并在您的清单中将活动声明为对话框。像这样

<activity
        android:name="com.example.DialogActivity"
        android:label="@string/app_name" 
        android:theme="@android:style/Theme.Dialog">

您能否再详细解释一下? - Ig0r82
非常感谢。最后一个问题。我需要从头开始构建警报还是只创建Java文件就可以工作? - Ig0r82
你只需要按照你想要的设计放置一些控件。然后根据你的需求编写一些逻辑。 - Harsh Goswami
Harsh你好,我已经发布了我的alertBox代码,有一个小问题我找不到解释。你能不能帮忙看一下? - Ig0r82
在调用 dialog.cancel() 后调用 finish();。 - Harsh Goswami

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接