当前位置: 动力学知识库 > 问答 > 编程问答 >

android - How to setup Alertbox from BroadcastReceiver

问题描述:

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();

}

}

网友答案:

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 :)

网友答案:

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" />
网友答案:

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

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

网友答案:

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>

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: