代码之家  ›  专栏  ›  技术社区  ›  Zelimir

从服务将警报对话框显示为系统覆盖窗口

  •  14
  • Zelimir  · 技术社区  · 14 年前

    显示服务中的AlertDialog时出现问题。我可以使用Toast或WindowManager(键入“系统警告”或“系统覆盖”)显示自定义布局窗口。但是,我不想使用自定义布局,我更喜欢直接使用漂亮的AlertDialog GUI。

    脚本:

    • 正在运行服务。没有活动的活动。
    • 在某些外部事件上,服务发送通知
    • 当用户按下通知时,通过PendingContent通知服务,应显示AlertDialog(创建时使用 AlertDialog.Builder(this) )

    错误:

    ERROR/AndroidRuntime(1063): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
    

    搜索答案会让我觉得我正在尝试一些目前不可能的东西(Android2.2)。或许是这样。

    2 回复  |  直到 10 年前
        1
  •  25
  •   brunobowden Dipak Keshariya    10 年前

    • super.setContentView() onCreate()

    android:theme="@android:style/Theme.Translucent"

        2
  •  6
  •   Programus    12 年前

    Intent.putExtra()

    DialogActivity onCreate()

    Intent intent = new Intent(this.getApplicationContext(), DialogActivity.class); 
    intent.putExtra(DialogActivity.CLASS_KEY, this.getClass().getCanonicalName());
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    

    private void returnOk(boolean ok) {
        Intent srcIntent = this.getIntent();
        Intent tgtIntent = new Intent();
        String className = srcIntent.getExtras().getString(CLASS_KEY);
        Log.d("DialogActivity", "Service Class Name: " + className);
        ComponentName cn = new ComponentName(this.getApplicationContext(), className);
        tgtIntent.setComponent(cn);
        tgtIntent.putExtra(RESULT_KEY, ok ? RESULT_OK : RESULT_CANCEL);
        this.startService(tgtIntent);
        this.finish();
    }
    

    onStartCommand()

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int ret = super.onStartCommand(intent, flags, startId);
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int result = extras.getInt(DialogActivity.RESULT_KEY, -1);
            if (result >= 0) {
                if (result == DialogActivity.RESULT_OK) {
                    // Your logic here...
                }
            } else {
                // Your other start logic here...
            }
        }
        return ret;
    }