Android - Service displayed Dialog

   This post talks about displaying a dialog via Service context by hijacking the token used for soft keyboards. Although it works, it is limited in its usage such as its location and might seem too much of a work for little gain.

   However, window manager service displays another type of Windows, WindowManager.LayoutParams.TYPE_TOAST to display toast messages. Toast messages can be shown by Activities and Services. This post is about reusing this window type to display the desired dialog.

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        LayoutInflater inflate = (LayoutInflater)
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View viewContainer = inflate.inflate( R.layout.custom_dialog, null);
        TextView view = ( TextView ) viewContainer.findViewById( R.id.text1 );
        Button button = ( Button ) viewContainer.findViewById( R.id.button1 );
        view.setText(" Service Dialog - Ok/Cancel? ");

        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.type = WindowManager.LayoutParams.TYPE_TOAST;
        params.x = 100;
        params.y = 100;

        final WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wm.removeViewImmediate( viewContainer );
            }
        });

        wm.addView(viewContainer, params);

        return START_NOT_STICKY;
}

The layout custom_dialog has a text view and two buttons and we have a Toast based dialog.


   This dialog is hosted in its own window and the view can receive focus and touch events. In this case, clicking Ok is going to dismiss the dialog by removing the view from Window Manager. Moreover, the default behavior is for the back button to be ignored and the user will have to dismiss the dialog window. This window wouldn't be dismissed even when the user presses the home key. There are other ways to trap those events and remove this dialog view accordingly.

No comments: