tags:

views:

61

answers:

2

This is my code:

public class Alarm extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Intent intent = new Intent(this, AlarmReceiver.class);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
        intent, PendingIntent.FLAG_ONE_SHOT);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent);
        Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();
    }
}

and

public final class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
    }
}

By the above code i am able to get the Toast. Instead of Toast I want the Dialog to be appear after the alarm is set. Also I want to play the sound.

Any one help me please?

A: 

There is a cool trick to do that.

Here are the steps to do it:

  • Place the BroadcastReceiver inside your Activity as an inner class.
  • Instead of adding the BroadcastReceiver in the manifest, you register yourself in the onStart() method of your Activity.
  • You unregister in the onPause() method of your Activity.
  • Inside the BroadcastReceiver you can call an Activity's method that do exactly what you ask for.
Macarse
That only works if the activity is going to be around. Typically, with `AlarmManager`, the point is for the activity to *not* be around.
CommonsWare
+1  A: 

You cannot display a Dialog from a BroadcastReceiver or Service. You will be better served using an Activity (perhaps one using Theme.Dialog) and calling startActivity().

Bear in mind, though, that users tend to really dislike it when background stuff pops up activities unannounced. For some apps -- alarm clocks, VOIP clients, etc. -- the user may be OK with it.

CommonsWare
CommonsWare, startActivity() is showing error in broadcatReceiver.
Sridhar Bandi
how can i use it..?
Sridhar Bandi