报警管理器有问题吗?
我在我的应用程序中使用 AlarmManager。我想在发生警报时向用户显示警告。 我使用了 AlertDialog 但它给出了一个错误。我该如何解决这个问题? 我想加上警告声音和振动。任何链接或代码。
public class AReceiver extends BroadcastReceiver{
AlertDialog alertDialog;
public void onReceive(Context context, Intent intent) {
alertDialog = new AlertDialog.Builder(this).create(); // Error here: The constructor AlertDialog.Builder is undefined.
alertDialog.setTitle("title");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
} });
}
}
I'm using AlarmManager in my app. I want to display the user a warning while alarm occurs.
I used an AlertDialog but it gives an error. How can I solve this problem?
And I want to put the warning sound and vibration. Any link or code.
public class AReceiver extends BroadcastReceiver{
AlertDialog alertDialog;
public void onReceive(Context context, Intent intent) {
alertDialog = new AlertDialog.Builder(this).create(); // Error here: The constructor AlertDialog.Builder is undefined.
alertDialog.setTitle("title");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
} });
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您好,您不能在
BroadcastReceiver
中使用 AlertDialog。您可以在
BroadcastReciver
中调用另一个 Activity 类,如下所示。在本课程中,您使用了警报对话框。
Hi you can not used AlertDialog in
BroadcastReceiver
..you call another Activity class in
BroadcastReciver
like below.And in this class you used Alert Dialog.
我可以向您展示如何解决这个问题的主要思想。
AlarmManager 中使用的 BroadcastReceiver 是一个具有静态上下文的静态类。
AlertDialog 应该在非静态上下文而不是静态上下文中执行。
对于这个问题我有两种解决方案。
使用非静态上下文向其他组件发送意图。
示例: https://github.com/yanfaxg/leaveme/blob/master/app/src/main/java/com/sunny/leaveme/AlarmHelper.java#L93
使用静态回调。并从非静态方法设置回调。
示例:
https: //github.com/sunnyleevip/leaveme/blob/master/app/src/main/java/com/sunny/leaveme/common/AlarmHelper.java
所以当你在非静态上下文中获取警报事件,可以使用AlertDialog。
I can show you the main idea of how to solve this problem.
The BroadcastReceiver using in the AlarmManager is a static class with static context.
AlertDialog should be executed in a non-static context instead of static context.
I have two solutions for this issue.
Send an intent to other components with non-static context.
example: https://github.com/yanfaxg/leaveme/blob/master/app/src/main/java/com/sunny/leaveme/AlarmHelper.java#L93
Use static callback. And set callback from a non-static method.
example:
https://github.com/sunnyleevip/leaveme/blob/master/app/src/main/java/com/sunny/leaveme/common/AlarmHelper.java
So when you get the alarm event in an non-static context, you can use AlertDialog.
迟到但可能对某人仍然有用:
更正代码如下:
Late but maybe still useful for someone:
Correct the code like below: