How to setup Alertbox from BroadcastReceiver
Asked Answered
P

4

1

I have implemented alarm in android app. Alarm is working fine. Toast message is visible. Now I want to make Alert Box Notification to user.

Here is code from ReceiverActivity Class. which I tried

public class ReceiverActivity extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

// Code....


    new AlertDialog.Builder(context)
    .setTitle("Alert Box")
    .setMessage("Msg for User")
    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int arg1) {
        // TODO Auto-generated method stub
            // some coding...
        }
    })
    .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface arg0, int arg1) {
            arg0.dismiss();
    }
}).create().show();
}

}

Papp answered 2/5, 2013 at 6:51 Comment(3)
whats the problem u r facing ?Ardeliaardelis
Why do you need a dialog to pop up spontaneously (from the user's point of view)? Why not use a Notification; that's what they're for.Crossroad
@PSK I updated my answer for more details ..... read about it..Tabathatabb
T
9

Although you can not show AlertDialog from Receivers because it needs ActivityContext.

You have an alternate solution to show an Activity like AlertDialog from Receiver. This is possible.

To start Activity as dialog you should set theme of activity in manifest as <activity android:theme="@android:style/Theme.Dialog" />

Style Any Activity as an Alert Dialog in Android


To start Activity from Receiver use code like

    //Intent mIntent = new Intent();
    //mIntent.setClassName("com.test", "com.test.YourActivity"); 
    Intent mIntent = new Intent(context,YourActivity.class) //Same as above two lines
    mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(mIntent);

And one more reason behind not using AlertDialog from receiver (Even if you managed to show AlertDialog) is

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.

In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service. More...

So the better way is 'show notification' and alternate way is 'to use Activity as an Alert..'

Happy coding :)

Tabathatabb answered 2/5, 2013 at 7:6 Comment(8)
It seems useful. let me try this. @Pankaj KumarPapp
can you explain me whats does setClassName() method do? @Pankaj KumarPapp
yes sure.. this is equivalent of new Intent(context,YourActivity.class) but here you need the full classname, including the package. You can use new Intent(context,YourActivity.class) too..Tabathatabb
nice explanation.. @Pankaj KumarPapp
this type of Intent can call from BroadcastReceiver to launch Alert Box@Pankaj KumarPapp
let us continue this discussion in chatTabathatabb
in my receiver method I put above code... when alert box popup then activity also open. but I don't need to open that activity. so is there any suggestion to do this?.. @Pankaj KumarPapp
how does whatsapp do it??Senhor
C
2

You can try to show dialog with sytem alert attributes:

YourAlertDialog dialog = new YourAlertDialog(mContext);
dialog.getWindow()
        .setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();

And Add system alert permission in your mainfest.xml:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
Clichy answered 2/5, 2013 at 7:10 Comment(2)
what is AdShowDialog in this code, I am getting error on this. @ClichyPapp
Sorry, I forget change the name. I copied the code from my project.Clichy
A
0

You cannot launch a popup dialog in your implementation of onReceive().

further information check AlertDialog from within BroadcastReceiver?? Can it be done?

Ardeliaardelis answered 2/5, 2013 at 6:58 Comment(2)
Ok @Richa.. I am checking your linkPapp
how does whatsapp do it??Senhor
M
0

I also looking for this solution but after searching lots of thing i did't get the exact ans for the custom dialog. So at this moment i make the custom dialog and pop up automatically when the internet connection gets down. So First of all we need to make a custom layout which we used for pop up so here is my alertforconnectioncheck.xml file

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fbutton="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:background="@color/colorPrimary"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="1dp"
    android:layout_marginLeft="2dp"
    android:layout_marginRight="2dp"
    android:layout_marginBottom="2dp"
    card_view:cardCornerRadius="7dp"
    card_view:cardElevation="10dp">

    <LinearLayout
        android:background="@color/colorPrimary"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="1">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/nonetwork1"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="3dp"
                android:layout_marginTop="11dp" />
        </LinearLayout>

        <LinearLayout
            android:layout_marginLeft="0dp"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:weightSum="1">

            <TextView
                android:id="@+id/text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="14dp"
                android:gravity="center"
                android:textColor="#fff"
                android:text="You are not connected to Internet!"
                android:layout_marginTop="16dp"
                android:layout_below="@+id/image"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true" />

            <info.hoang8f.widget.FButton
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:drawablePadding="0dp"
                android:minWidth="150dp"
                android:paddingLeft="30dp"
                android:paddingRight="20dp"
                android:paddingTop="5dp"
                android:paddingBottom="10dp"
                fbutton:cornerRadius="15dp"
                android:layout_gravity="center"
                android:gravity="center"
                fbutton:shadowEnabled="true"
                fbutton:shadowHeight="5dp"
                android:id="@+id/ok_button"
                android:textColor="@android:color/white"
                android:text="OK"
                android:layout_marginTop="22dp"
                android:layout_below="@+id/text"
                android:layout_centerHorizontal="true" />
        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>

enter image description here Now make the Broadcast extendable class:

public class NetworkChangeReceiver extends BroadcastReceiver {
    String LOG_TAG = "NetworkChangeReceiver";
    public boolean isConnected = false;
    private SharedPreferences.Editor edit;
    private Boolean status;
    @Override
    public void onReceive(final Context context, final Intent intent) {

        Log.v(LOG_TAG, "Receieved notification about network status");
        status = isNetworkAvailable(context);

        if (status == false) {

            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.alertforconnectioncheck);
            dialog.setTitle("No Internet Connection...");
            Button dialogButton = (Button) dialog.findViewById(R.id.ok_button);
            dialogButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        if(!isConnected){
                            Log.v(LOG_TAG, "Now you are connected to Internet!");
                            Toast.makeText(context, "Now you are connected to Internet!", Toast.LENGTH_LONG).show();
                            isConnected = true;
                        }
                        return true;
                    }
                }
            }
        }
        Log.v(LOG_TAG, "You are not connected to Internet!");
        Toast.makeText(context, "You are not connected to Internet!", Toast.LENGTH_LONG).show();
        isConnected = false;
        return false;
    }
}

Now in MainActivity Class call the Broadcast Receiver class in onCreate:

private NetworkChangeReceiver receiver;
IntentFilter filter;
filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetworkChangeReceiver();
        registerReceiver(receiver, filter);  

This is the custom dialog box which appear automatically when the internet gets down and if you have a multiple Activities in the application you must be call it in every activity in the onCreate hope it helps for some one who looking for this solution.

Mendes answered 14/12, 2016 at 8:5 Comment(1)
i am getting exception android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an applicationGaur

© 2022 - 2024 — McMap. All rights reserved.