Displaying OK dialog from service / receiver on Android

There is a receiver in my application that is called when an SMS message is received. I want to notify the user with a simple 1 button dialog.

This is my code:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("Hello dude").setCancelable(false).setPositiveButton("Got you", new DialogInterface.OnClickListener() {


            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                //mp.stop();

            }
        }).show();

But this throws an exception:

android.view.WindowManager $ BadTokenException

Please, help...

+3
source share
4 answers

Firstly, you cannot display a dialog with Serviceor BroadcastReceiver.

Secondly, DO NOT INTERRUPT THE USER. The right way to tell the user what happened in the background is to show Notification.

+5
source

Here's what I did: from my service instance, I run the following view:

final Intent dialog = new Intent(this, BackGroundDialogs.class);
dialog.setType("text/plain");
dialog.putExtra(android.content.Intent.EXTRA_TEXT, reason);
dialog.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(dialog);

as for the BackGround Dialogs class, it looks like this:

/**
 * @ To create the illusion of a alert window displayed on its own when app is
 * in the background. Really, this is a Activity but its only displaying an
 * alert window and the Activity borders have been removed.
 */
public class BackGroundDialogs extends Activity {

    public BroadcastReceiver receiver;
    public AlertDialog mAlert;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE); // custom theme with
                                                            // no borders
        IntentFilter filter = new IntentFilter();
        filter.addAction(Consts.DISMISS_DIALOG);// we can dismiss it via an
                                                // intent if we choose
        receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, final Intent intent) {
                // do something based on the intent action
                if (context == null) return;
                if (intent.getAction().equals(Consts.DISMISS_DIALOG)) {
                    finish();
                }
            }
        };
        registerReceiver(receiver, filter);
    }

    /**
     * @brief Shows an alert message using a Dialog window.
     * @param reason
     *            :the message you wish to display in the alert
     */
    public void showAlert(final String reason) {
        mAlert = new AlertDialog.Builder(this).create();
        mAlert.setCancelable(false);
        TextView Msg_tv = new TextView(this);
        Msg_tv.setTypeface(null, Typeface.BOLD);
        Msg_tv.setTextSize(16.0f);
        Msg_tv.setText(reason);
        Msg_tv.setGravity(Gravity.CENTER_HORIZONTAL);
        mAlert.setView(Msg_tv);
        mAlert.setButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        mAlert.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Bundle extras = getIntent().getExtras();
        String reason = extras.getString(Intent.EXTRA_TEXT);
        if (reason.equalsIgnoreCase("DISMISS")) finish();
        else showAlert(reason);// invoke the new dialog to show
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAlert != null) if (mAlert.isShowing()) mAlert.dismiss();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

BroadcastReceiver, , , .

+2

Raheem ... you can start working with the service the way you start your activity with activiy

Intent newActivity = new Intent(context,servicename.class);
context.startService(newActivity);

Context must be application context

0
source

You can do this using TYPE_SYSTEM_ALERT:

AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("Title")
                    .setMessage("Hello dude")
                    .setCancelable(false)
                    .setPositiveButton("Got you", new DialogInterface.OnClickListener() {
                        @Override public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            //mp.stop();
                        }
                    }).create();

alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();

Please note that you must use the following permission:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
0
source

Source: https://habr.com/ru/post/1794908/


All Articles