Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

android - How to raise an alert dialog from BroadcastReceiver class?

I have used a timer method in an Activity class. In that method I have an intent from Activity class to a BroadcastReceiver class.

This BroadcastReceiver class will call on every 15 minutes at background by using AlarmManager.

When I call the BroadcastReceiver class I would like to raise an AlertDialog.

public void timerMethod(){
    Intent intent = new Intent(Activity.this,
      BroadcastReceiverClass.class
    );

    PendingIntent sender = PendingIntent.getBroadcast(
      QualityCallActivity.this,0, intent, 0
    );

    // We want the alarm to go off 30 seconds from now.
    long firstTime = SystemClock.elapsedRealtime();

    AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    firstTime, 60*1000, sender);
}

BroadcastReceiverClass.java

public void onReceive(Context context, Intent intent)
{
    dialogMethod();
}

How can I raise an AlertDialog from BroadcastReceiver class from a background process?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your activity is running when the BroadcastReceiver gets the intent you should be able to use runOnUiThread to run a method that creates an AlertDialog, e.g.:

public void onReceive(Context context, Intent intent)
{
    runOnUiThread(new Runnable() {
        public void run() {
            AlertDialog.Builder d = new AlertDialog.Builder(MyActivity.this);
            b.setMessage("This is a dialog from within a BroadcastReceiver");
            b.create().show();
        }
    });

}

This works if you make your BroadcastReceiver an inner class to your Activity.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...