开发者

AlarmManager problem?

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开发者_JAVA技巧 AlertDialog.Builder is undefined.
     alertDialog.setTitle("title");

     alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

          public void onClick(DialogInterface dialog, int which) {
            return;
        } });

 }
}


Hi you can not used AlertDialog in BroadcastReceiver..

you call another Activity class in BroadcastReciver like below.

Intent myIntent = new Intent(context, AlarmActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);

And in this class you used Alert Dialog.


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:

alertDialog = new AlertDialog.Builder(context).create(); // Now The constructor AlertDialog.Builder is defined.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜