从android中的服务弹出警报对话框

时间:2014-01-22 12:56:03

标签: android service android-alertdialog

我正在尝试构建活动感知应用。 我使用Android开发人员的活动识别示例作为起点。 在此示例中,用户开始移动通知的那一刻出现,并请求打开GPS。 我正在尝试用警报对话框和一些声音替换此通知。 我找到的简单且最常见的警报框对我不起作用,因为从服务中创建一个不合格是不可能的。 感谢Harsh给我一个活动的想法。 我将在它工作的那一刻发布代码。 先感谢您 承诺从服务调用的警报框的工作代码: 1)服务文件中的代码:

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

2)警报活动.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>

一切正常,有一件事仍然存在问题,当我按下确定按钮时,应用程序关闭但应用程序的标签保持不变直到我点击屏幕。

1 个答案:

答案 0 :(得分:8)

从服务启动活动,并在清单中将活动声明为对话框。喜欢这个

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