Show Dialog using PendingIntent

旧城冷巷雨未停 提交于 2019-11-29 04:29:32

In your Receiver class, just code to get the dialog to display instead of Notification.

Class that displays Dialog:

public class AlarmDialogPopUp extends Activity
{

    private int m_alarmId;

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

        // Get the alarm ID from the intent extra data
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();

        if (extras != null) {
            m_alarmId = extras.getInt("AlarmID", -1);
        } else {
            m_alarmId = -1;
        }

        // Show the popup dialog
        showDialog(0);
    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
        super.onCreateDialog(id);

        // Build the dialog
        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("ALARM REMINDER");
        alert.setMessage("Its time for the alarm ");
        alert.setCancelable(false);

        alert.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                AlarmDialogPopUp.this.finish();
            }
        });

        // Create and return the dialog
        AlertDialog dlg = alert.create();

        return dlg;
    }
}

In your onReceive to show dialog :

public void onReceive(Context context, Intent intent)
    {
          // Launch the alarm popup dialog
            Intent alarmIntent = new Intent("android.intent.action.MAIN");

            alarmIntent.setClass(context, AlarmDialogPopUp .class);
            alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Pass on the alarm ID as extra data
            alarmIntent.putExtra("AlarmID", intent.getIntExtra("AlarmID", -1));

            // Start the popup activity
            context.startActivity(alarmIntent);

    }

EDIT based on the comment:

To play sound, you need to make use of MediaPlayer like below.

Add this line in the onCreate() of AlarmDialogPopUp activity class to play the sound.

MediaPlayer mediaPlayer; //global variable.

    mediaPlayer = MediaPlayer.create(this,R.raw.alarmsound);

Add the below lines in the onClick() of the dialog to stop the sound:

mediaPlayer.stop();
mediaPlayer.release();

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!