Service中使用AlertDialog

在Service中使用Dialog,遇到问题

    private void showRtspConnectedDialog() {
        Log.d(TAG, "showRtspConnectedDialog xxx");
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setMessage("确认退出吗?");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        builder.create().show();
    }

报错,导致系统一会重启: 

 AndroidRuntime: *** FATAL EXCEPTION IN SYSTEM PROCESS: android.server.ServerThread
 AndroidRuntime: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
 AndroidRuntime: at android.view.ViewRootImpl.setView(ViewRootImpl.java:668)
 AndroidRuntime: at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
 AndroidRuntime: at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
 AndroidRuntime: at android.app.Dialog.show(Dialog.java:281)
 AndroidRuntime: at com.android.server.display.DongleManagerService.showRtspConnectedDialog(DongleManagerService.java:566)
 AndroidRuntime: at com.android.server.display.DongleManagerService.access$2200(DongleManagerService.java:38)
 AndroidRuntime: at com.android.server.display.DongleManagerService$7.handleMessage(DongleManagerService.java:940)
 AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:107)
 AndroidRuntime: at android.os.Looper.loop(Looper.java:194)
 AndroidRuntime: at com.android.server.ServerThread.run(SystemServer.java:1353


这样写就没有事了,参照WifiP2pService.java

    private void showRtspConnectedDialog() {
        Resources r = Resources.getSystem();
        AlertDialog dialog = new AlertDialog.Builder(mContext)
        .setTitle(r.getString(R.string.wifi_p2p_dialog_title))
        .setMessage(r.getString(R.string.wifi_p2p_failed_message))
        .setPositiveButton(r.getString(R.string.ok), null)
        .create();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();
    }

希望对以后在service中使用对话框有帮助


你可能感兴趣的:(Service中使用AlertDialog)