android闹钟的制作

首先获取闹钟管理者AlarmManager,通过button中的方法setAlarmOne()实现:
1.获取当前Calendar系统时间
2.弹出时间对话框
//3.确定好选择的时间TimePickerDialog,(TimePickerDialog时间选择器)
//4.设置闹钟
//5.当之间一到Intent实现跳转,将执行的响应(intent.setAction(“com.example.g150831_android28_alarm_notification.RING”);)

 private AlarmManager alarmManager;



  //获取闹钟管理者
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);




   public void setAlarmOne(View view){
        //获取当前系统时间
        Calendar calendar=Calendar.getInstance();
        int hour=calendar.get(Calendar.HOUR_OF_DAY);
        int minute=calendar.get(Calendar.MINUTE);


        //01.弹出时间对话框
        TimePickerDialog timePickerDialog=new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int i, int i1) {
                Calendar c=Calendar.getInstance();
                c.set(Calendar.HOUR_OF_DAY,i);
                c.set(Calendar.MINUTE,i1);
                //02.确定好选择的时间
                //03.设置闹钟

                //04.当之间一到,将执行的响应
                Intent intent=new Intent();
                intent.setAction("com.example.g150831_android28_alarm_notification.RING");
                PendingIntent pendingIntent=PendingIntent.getBroadcast(MainActivity.this,0x101,intent,0);
                alarmManager.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);


            }
        },hour,minute,true);
        timePickerDialog.show();



    }


  public void cancelAlarmCycle(View view){
        alarmManager.cancel(pendingIntent);
    }

新建一个activity 类RingReceived,通过广播 extends BroadcastReceiver实现
广播的传输

 @Override
    public void onReceive(Context context, Intent intent) {
   //com.example.g150831_android28_alarm_notification项目名称     if("com.example.g150831_android28_alarm_notification.RING".equals(intent.getAction())){
//给intent设置标志位Flag
            Log.i("test","收到广播了");
            //跳转到Activity
            Intent intent1=new Intent(context,RingActivity.class);
            //给Intent设置标志位Flag
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //Intent的组成部分:ComponementName extra  Action Data Categlay(分组) Flag
            context.startActivity(intent1);
        }

在新建一个Activity ,当时间一到就跳到这个Activity ,实现一些操作

        //播放音乐
        mediaPlayer = MediaPlayer.create(this, R.raw.duo);
//开始播放
        mediaPlayer.start();


//关闭mediaPlayer
public void close(View view){
    mediaPlayer.stop();
    finish();

}

必须在androidmanifest.xml中配置广播的传输
//android:name=”com.example.g150831_android28_alarm_notification.RING”需要和广播的activaty一致

 <receiver android:name=".RingReceived">
            <intent-filter
                >
                <action android:name="com.example.g150831_android28_alarm_notification.RING" >action>


            intent-filter>

你可能感兴趣的:(安卓,系统广播)