1

Androidアプリにアラームを実装しました。アラームは正常に動作しています。Toastメッセージが表示されます。 今私はユーザーにアラートボックス通知をしたいと思います

ReceiverActivityクラスのコードは次のとおりです。私が試した

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

}

4

4 に答える 4

9

ただし、ActivityContext が必要なため、Receiver から AlertDialog を表示することはできません。

Receiver から AlertDialog のようなアクティビティを表示する代替ソリューションがあります。これは可能です。

アクティビティをダイアログとして開始するには、マニフェストでアクティビティのテーマを次のように設定する必要があります<activity android:theme="@android:style/Theme.Dialog" />

Android で任意のアクティビティをアラート ダイアログとしてスタイル設定する


レシーバーからアクティビティを開始するには、次のようなコードを使用します

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

そして、レシーバーから AlertDialog を使用しないもう 1 つの理由 (AlertDialog を表示できたとしても) は、

BroadcastReceiver オブジェクトは、onReceive(Context, Intent) への呼び出しの間のみ有効です。コードがこの関数から戻ると、システムはオブジェクトが終了し、アクティブではなくなったと見なします。

これは、 onReceive(Context, Intent) 実装でできることに重要な影響を与えます。非同期操作を処理するには関数から戻る必要があるため、非同期操作を必要とするものはすべて利用できませんが、その時点で BroadcastReceiver はアクティブではなくなるため、システムは非同期操作が完了する前にそのプロセスを自由に強制終了できます。

特に、ダイアログを表示したり、 BroadcastReceiver 内からサービスにバインドしたりすることはできません。前者の場合は、代わりに NotificationManager API を使用する必要があります。後者の場合、 Context.startService() を使用してコマンドをサービスに送信できます。もっと...

したがって、より良い方法は「通知を表示する」ことであり、別の方法は「アクティビティをアラートとして使用することです..」

ハッピーコーディング:)

于 2013-05-02T07:06:39.827 に答える
2

システムアラート属性を含むダイアログを表示することを試みることができます:

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

また、mainfest.xml にシステム アラート権限を追加します。

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
于 2013-05-02T07:10:05.983 に答える
0

私もこの解決策を探していますが、多くのものを検索した後、カスタムダイアログの正確な答えが得られませんでした. そのため、現時点でcustom dialogは、インターネット接続がダウンしたときに自動的にポップアップするようにしています。まず、ポップアップに使用するカスタム レイアウトを作成する必要があるので、ここに私のalertforconnectioncheck.xmlファイル を示します。

<?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>

ここに画像の説明を入力 次に、Broadcast 拡張可能クラスを作成します。

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;
    }
}

MainActivity クラスで、次のブロードキャスト レシーバー クラスを呼び出しますonCreate

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

これは、インターネットがダウンしたときに自動的に表示されるカスタム ダイアログ ボックスです。アプリケーションに複数ある場合は、このソリューションを探している人に役立つことを期待し Activitiesて、すべてのアクティビティで呼び出す必要があります。onCreate

于 2016-12-14T08:05:17.837 に答える