Android:Moring-早安闹钟开发过程记录(二)

续接上一篇文章

1.叫醒功能实现

  • 叫醒对话框
    这个对话框是不是很丑啊?这个对话框之所以丑的原因是因为我懒~


    闹钟对话框.png


    分析一下这个对话框的特点,就是三点

    • a.要根据用户选择的赖床指数显示不同难度的题目
    • b.要将用户输入的结果跟正确答案进行对比
    • c.不允许退出(这样才能达到暴力叫醒),返回键也无效
      a
      在dialog上的代码就是setMessage(),在AlarmReceiverzhong 根据LazyLevel生成两个随机数
      private int youCantSleep() {
      Random a=new Random();
      if(lazylevel==1){A = a.nextInt(20)+5;B = a.nextInt(20)+5;
      }else if(lazylevel==2){A = a.nextInt(99)+1;B = a.nextInt(99)+1;while(B<50) B+=10;
      }else if(lazylevel==3){A = a.nextInt(200)+1;B = a.nextInt(200)+1;while (B<80)    B+=10;while(A<80)    A+=10;
      }else if(lazylevel==4){A = a.nextInt(500)+1;B = a.nextInt(500)+1;while(B<80)    B+=10;while(A<200)    A+=30;
      } 
      return A*B;
      }
      b
      这个比较简单,positiveButton的监听中if判断一下正确答案和输入答案,正确的话就dialog.dismiss();
      c
      -首先Alertdialog.Builder有一个方法setCancelable(false);传入false将不可以点击取消,点击Home键都不可以被取消,只能通过确定。当然杀进程是可以的~
      builder.setCancelable(false);
      -然后将dialog设置成为系统级别
      AlertDialog dialog=builder.create();
      WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
      params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
      这里需要一个权限
  • 播放闹钟铃声
    启动一个Service来播放音乐,播放的音乐由AlarmReceiver通过Intent传递过去

    • 启动AlarmService
      Intent service=new Intent(context, AlarmRingService.class);
      service.putExtra("resid", resid);
      context.startService(service);
    • AlarmService在onStartCommand中获取到数据
      //拿到用户选择的那个铃声
      Song=intent.getStringExtra("resid");if (Song==null){
      //    为了程序的健壮性,判断一下,以免出现不必要的异常Song="everybody.mp3";}
      ringTheAlarm(Song);
    • 播放音乐(MediaManager)
      核心代码
      mPlayer=new MediaPlayer();
      assetFileDescriptor = this.getAssets().openFd(song);
      mPlayer.reset();
      mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
      mPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
      重点
      mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
      注意 该方法必须在prepare()之前调用,否则无效!
      该方法将这个MediaPlayer设置成为某一个特定的媒体类型,这里设置成为STREAM_ALARM,这样可以实现调节闹钟音量不会影响其他音量,避免用户设置为手机静音后闹钟失效。
  • 开启震动

    private void startVibrate() {mVibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);if(mVibrator.hasVibrator()){mVibrator.vibrate(new long[]{500, 1500, 500, 1500}, 0);//off on off on  repeatmode}
    }
  • 停止服务
    当用户关闭闹钟时停止服务,因此关闭音乐和关闭震动的代码写在onDestroy中
    @Overridepublic
    void onDestroy() {super.onDestroy();stopTheAlarm();stopVibrate();
    }

    结尾

    简单记录了下开发的思路,以及一些小的,但是容易漏掉的知识点,调试的时候会很让人抓狂的。下一篇文章分析FragmentWeather中实现的逻辑
未完待续...


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部