系统重启后,在广播接收器中显示警告对话框

iro*_*xxx 31 android

美好的一天,我试图在广播接收器中重新启动系统后显示一个警告对话框.我在清单中添加了接收器并调用了所需的权限,但在显示对话框时出错.请问我怎样才能正确实现这一点?...谢谢

我的代码:

public void onReceive(final Context context, Intent intent) {
    Log.d(TAG, "received boot completed broadcast receiver... starting settings");


    String settings = context.getResources().getString(R.string.restart_setting);
        String yes = context.getResources().getString(R.string.Settings);
        String no = context.getResources().getString(R.string.Cancel);

              final AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMessage(settings)
                       .setCancelable(false)
                       .setPositiveButton(yes, new DialogInterface.OnClickListener() {
    public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) 
   Intent config = new Intent(context, WeatherConfigure.class)
     context.startActivity(config);

    }
 })
    .setNegativeButton(no, new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
             dialog.cancel();
        }
    });
  final AlertDialog alert = builder.create();
  alert.show();

    }
Run Code Online (Sandbox Code Playgroud)

我收到此日志错误:

01-07 01:42:01.559: ERROR/AndroidRuntime(2004): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

01-07 01:42:01.559: ERROR/AndroidRuntime(2004): at android.view.ViewRoot.setView(ViewRoot.java:548)

01-07 01:42:01.559: ERROR/AndroidRuntime(2004):at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)

01-07 01:42:01.559: ERROR/AndroidRuntime(2004): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)

01-07 01:42:01.559: ERROR/AndroidRuntime(2004):at android.app.Dialog.show(Dialog.java:288)

01-07 01:42:01.559: ERROR/AndroidRuntime(2004):at com.MuaaApps.MyWeatherUpdate.myWeatherBroadcastReceiver.onReceive(MyWeatherBroadcastReceiver.java:59)

01-07 01:42:01.559: ERROR/AndroidRuntime(2004): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1994)
Run Code Online (Sandbox Code Playgroud)

cod*_*e22 47

问题是你试图AlertDialog从a中显示一个BroadcastReceiver,这是不允许的.你无法展示AlertDialog一个BroadcastReceiver.只有活动才能显示对话框.

您应该执行其他操作,在BroadcastReceiver启动时启动并启动活动以显示对话框.

这是一篇更多关于此的博客文章.

编辑:

以下是我推荐的方法.从你BroadcastReceiver开始了ActivityAlertDialog这样..

public class NotifySMSReceived extends Activity 
{
    private static final String LOG_TAG = "SMSReceiver";
    public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
    static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IntentFilter filter = new IntentFilter(ACTION);
        this.registerReceiver(mReceivedSMSReceiver, filter);
    }

    private void displayAlert()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to exit?").setCancelable(
            false).setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            }).setNegativeButton("No",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private final BroadcastReceiver mReceivedSMSReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION.equals(action)) 
            {
                //your SMS processing code
                displayAlert();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如你所见,我从不打电话setContentView().这是因为活动将具有透明视图,并且仅显示警报对话框.

  • 谢谢你的答案,但活动有黑色背景. (2认同)

Bhi*_*bim 27

你不能在BroadcastReceiver上使用对话框,所以你最好从BroadcastReceiver调用对话框的一个活动,

在onReceive函数中添加此代码:

@Override
public void onReceive(Context context, Intent intent) 
{
    Intent i = new Intent(context, {CLASSNAME}.class); 
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    context.startActivity(i);
}
Run Code Online (Sandbox Code Playgroud)

用对话框活动填充{CLASSNAME},继承我的对话活动:

package com.example.mbanking;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;


// ALERT DIALOG
// Sources : http://techblogon.com/alert-dialog-with-edittext-in-android-example-with-source-code/

public class AlertDialogActivity extends Activity 
{

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder
        .setTitle("Test")
        .setMessage("Are you sure you want to exit?")
        .setCancelable(false)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int id) 
            {
                dialog.cancel();
            }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int id) 
            {
                dialog.cancel();
            }
        });
    AlertDialog alert = builder.create();
    alert.show();
}
}
Run Code Online (Sandbox Code Playgroud)

我得到答案的地方?,这里:你如何在android的广播接收器中使用警告对话框? 感谢Femi !!,我只传播新闻:D

  • @Bhimbim 它不起作用我不知道为什么人们会赞成这个答案。 (2认同)

Nik*_*dze 7

这是一篇关于如何做的帖子.您可以从这里获取源代码.

您无法直接从广播接收器显示对话框.你必须使用Activity.此外,为了接收ACTION_BOOT_COMPLETED您的活动,必须首先由用户或其他应用程序明确启动(谷歌应用程序停止状态以获取更多信息).

基本上,要实现所需的功能,您需要:

  1. 创建显示对话框的透明活动.
  2. 创建BroadcastReceiver接收ACTION_BOOT_COMPLETED并开始您的活动.
  3. 在清单中注册您的广播接收器并获得适当的许可.

此外,问题提供了有关如何创建透明活动的更多信息.


小智 7

最好的方法是制作一个活动并将其“主题”属性设置为“Theme.Translucen”

 <activity
        android:name=".MyAlertDialog"
        android:label="@string/title_activity_alert_dialog"
        android:launchMode="singleInstance"
        android:theme="@android:style/Theme.Translucent" >
    </activity>
Run Code Online (Sandbox Code Playgroud)

并在您的活动中创建一个警报对话框:

public class MyAlertDialog extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE); //hide activity title
    setContentView(R.layout.activity_my_alert_dialog);

    AlertDialog.Builder Builder=new AlertDialog.Builder(this)
            .setMessage("Do You Want continue ?")
            .setTitle("exit")
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setNegativeButton(R.string.No, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MyAlertDialog.this.finish();
                }
            })
            .setPositiveButton(R.string.Yes,null);
    AlertDialog alertDialog=Builder.create();
    alertDialog.show();

}

}
Run Code Online (Sandbox Code Playgroud)

并在 brodcastreciver 中:

 @Override
public void onReceive(Context context, Intent intent) {

    Intent i=new Intent(context.getApplicationContext(),MyAlertDialog.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);

}
}
Run Code Online (Sandbox Code Playgroud)