【问题标题】:Alarm Repeats Infinitely -- Locking up phone警报无限重复——锁定手机
【发布时间】:2015-06-27 17:27:17
【问题描述】:

闹钟的日期和时间分别创建,然后设置一个闹钟为:

public void schedule(Context context) {
    setAlarmActive(true);

    Intent myIntent = new Intent(context, AlarmAlertBroadcastReciever.class);
    myIntent.putExtra("alarm", this);

    // Adding random signature
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Previously setting the time
    //alarmManager.set(AlarmManager.RTC_WAKEUP, getAlarmTime().getTimeInMillis(), pendingIntent);

    // Testing adding the alarm date to this
    Calendar alarmSchedule = Calendar.getInstance();

    // Setting the time:
    alarmSchedule.set(Calendar.HOUR, getAlarmTime().get(Calendar.HOUR));
    alarmSchedule.set(Calendar.MINUTE, getAlarmTime().get(Calendar.MINUTE));
    alarmSchedule.set(Calendar.SECOND, 0);

    // Setting the date:
    alarmSchedule.set(Calendar.YEAR, alarmDate.get(Calendar.YEAR));
    alarmSchedule.set(Calendar.MONTH, alarmDate.get(Calendar.MONTH));
    alarmSchedule.set(Calendar.DAY_OF_MONTH, alarmDate.get(Calendar.DAY_OF_MONTH));

    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmSchedule.getTimeInMillis(), pendingIntent);
}

闹钟确实在正确的日期和时间响起,但当它响起时,它会无限重复警告对话框,就像一个无限循环,锁定手机,直到用户必须重新启动设备并删除闹钟。

我该如何缓解这个问题?

设置日期:

  public void setAlarmDate(Calendar alarmDate) {
        this.alarmDate = alarmDate;
    }

    public void setAlarmDate(String alarmDate) {

        String[] datePieces = alarmDate.split("-");
        Log.v("setAlarmDate-Year", datePieces[0]);
        Log.v("setAlarmDate-Month", datePieces[1]);
        Log.v("setAlarmDate-Day", datePieces[2]);

        Calendar newAlarmDate = Calendar.getInstance();

        // Taking from above, adding now a specific date
        newAlarmDate.set(Calendar.YEAR,
                Integer.parseInt(datePieces[0]));
        newAlarmDate.set(Calendar.MONTH,
                Integer.parseInt(datePieces[1]) - 1); 
        newAlarmDate.set(Calendar.DAY_OF_MONTH,
                Integer.parseInt(datePieces[2]));
        setAlarmDate(newAlarmDate);

    }

设置时间: 公共无效 setAlarmTime(日历闹钟时间){ this.alarmTime = 闹钟时间; }

public void setAlarmTime(String alarmTime) {

    String[] timePieces = alarmTime.split(":");

    Calendar newAlarmTime = Calendar.getInstance();
    newAlarmTime.set(Calendar.HOUR_OF_DAY,
            Integer.parseInt(timePieces[0]));
    newAlarmTime.set(Calendar.MINUTE, Integer.parseInt(timePieces[1]));
    newAlarmTime.set(Calendar.SECOND, 0);
    setAlarmTime(newAlarmTime);
}

广播接收者:

public class AlarmAlertBroadcastReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent mathAlarmServiceIntent = new Intent(
                context,
                AlarmServiceBroadcastReciever.class);
        context.sendBroadcast(mathAlarmServiceIntent, null);

        StaticWakeLock.lockOn(context);
        Bundle bundle = intent.getExtras();
        final Alarm alarm = (Alarm) bundle.getSerializable("alarm");

        Intent mathAlarmAlertActivityIntent;

        mathAlarmAlertActivityIntent = new Intent(context, AlarmAlertActivity.class);

        // Should create a notification that event is occurring
        mathAlarmAlertActivityIntent.putExtra("alarm", alarm);

        mathAlarmAlertActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        context.startActivity(mathAlarmAlertActivityIntent);
    }

}

AlarmServiceBroadcastReciever 类:

public class AlarmServiceBroadcastReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("AlarmServiceBroadcastReciever", "onReceive()");
        Intent serviceIntent = new Intent(context, AlarmService.class);
        context.startService(serviceIntent);
    }

}

报警服务类:

public class AlarmService extends Service {

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onCreate()
     */
    @Override
    public void onCreate() {
        Log.d(this.getClass().getSimpleName(),"onCreate()");
        super.onCreate();       
    }

    private Alarm getNext(){
        Set<Alarm> alarmQueue = new TreeSet<Alarm>(new Comparator<Alarm>() {
            @Override
            public int compare(Alarm lhs, Alarm rhs) {
                int result = 0;
                long diff = lhs.getAlarmTime().getTimeInMillis() - rhs.getAlarmTime().getTimeInMillis();                
                if(diff>0){
                    return 1;
                }else if (diff < 0){
                    return -1;
                }
                return result;
            }
        });

        Database.init(getApplicationContext());
        List<Alarm> alarms = Database.getAll();

        for(Alarm alarm : alarms){
            if(alarm.getAlarmActive())
                alarmQueue.add(alarm);
        }
        if(alarmQueue.iterator().hasNext()){
            return alarmQueue.iterator().next();
        }else{
            return null;
        }
    }
    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onDestroy()
     */
    @Override
    public void onDestroy() {
        Database.deactivate();
        super.onDestroy();
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(this.getClass().getSimpleName(),"onStartCommand()");
        Alarm alarm = getNext();
        if(null != alarm){
            alarm.schedule(getApplicationContext());
            Log.d(this.getClass().getSimpleName(),alarm.getTimeUntilNextAlarmMessage());

        }else{
            Intent myIntent = new Intent(getApplicationContext(), AlarmAlertBroadcastReciever.class);
            myIntent.putExtra("alarm", new Alarm());

            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, myIntent,PendingIntent.FLAG_CANCEL_CURRENT);           
            AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);

            alarmManager.cancel(pendingIntent);
        }
        return START_NOT_STICKY;
    }

}

AlarmAlertActivity:

public class AlarmAlertActivity extends Activity implements OnClickListener {

    private Alarm alarm;
    private MediaPlayer mediaPlayer;

    private StringBuilder answerBuilder = new StringBuilder();

    //private MathProblem mathProblem;
    private Vibrator vibrator;

    private boolean alarmActive;
    private NotificationManager mNotificationManager;
    public static final int NOTIFICATION_ID = 1;

    private TextView problemView;
    private TextView answerView;
    private String answerString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        setContentView(R.layout.alarm_alert);

        Bundle bundle = this.getIntent().getExtras();
        alarm = (Alarm) bundle.getSerializable("alarm");


        ((Button) findViewById(R.id.openEvent)).setOnClickListener(this);

        TelephonyManager telephonyManager = (TelephonyManager) this
                .getSystemService(Context.TELEPHONY_SERVICE);

        PhoneStateListener phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    Log.d(getClass().getSimpleName(), "Incoming call: "
                            + incomingNumber);
                    try {
                        mediaPlayer.pause();
                    } catch (IllegalStateException e) {

                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.d(getClass().getSimpleName(), "Call State Idle");
                    try {
                        mediaPlayer.start();
                    } catch (IllegalStateException e) {

                    }
                    break;
                }
                super.onCallStateChanged(state, incomingNumber);
            }
        };

        telephonyManager.listen(phoneStateListener,
                PhoneStateListener.LISTEN_CALL_STATE);

        // Toast.makeText(this, answerString, Toast.LENGTH_LONG).show();

        startAlarm();

    }

    @Override
    protected void onResume() {
        super.onResume();
        alarmActive = true;
    }

    private void startAlarm() {

        if (alarm.getAlarmTonePath() != "") {
            mediaPlayer = new MediaPlayer();
            if (alarm.getVibrate()) {
                vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                long[] pattern = { 1000, 200, 200, 200 };
                vibrator.vibrate(pattern, 0);
            }
            try {
                mediaPlayer.setVolume(1.0f, 1.0f);
                mediaPlayer.setDataSource(this,
                        Uri.parse(alarm.getAlarmTonePath()));
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mediaPlayer.setLooping(true);
                mediaPlayer.prepare();
                mediaPlayer.start();

            } catch (Exception e) {
                mediaPlayer.release();
                alarmActive = false;
            }
        }

    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
        if (!alarmActive)
            super.onBackPressed();
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onPause()
     */
    @Override
    protected void onPause() {
        super.onPause();
        StaticWakeLock.lockOff(this);
    }

    @Override
    protected void onDestroy() {
        try {
            if (vibrator != null)
                vibrator.cancel();
        } catch (Exception e) {

        }
        try {
            mediaPlayer.stop();
        } catch (Exception e) {

        }
        try {
            mediaPlayer.release();
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        String button = (String) v.getTag();
        if (!alarmActive)
            return;

        // When click the view, shut off the alarm
        alarmActive = false;
        if (vibrator != null)
            vibrator.cancel();
        try {
            mediaPlayer.stop();
        } catch (IllegalStateException ise) {

        }
        try {
            mediaPlayer.release();
        } catch (Exception e) {

        }

        // and show the details:
        Intent getEvent = new Intent(this, AlarmActivity.class);
        startActivity(getEvent);



        this.finish();

//      v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
//      if (button.equalsIgnoreCase("clear")) {
//          if (answerBuilder.length() > 0) {
//              answerBuilder.setLength(answerBuilder.length() - 1);
//              answerView.setText(answerBuilder.toString());
//          }
//      } else if (button.equalsIgnoreCase(".")) {
//          if (!answerBuilder.toString().contains(button)) {
//              if (answerBuilder.length() == 0)
//                  answerBuilder.append(0);
//              answerBuilder.append(button);
//              answerView.setText(answerBuilder.toString());
//          }
//      } else if (button.equalsIgnoreCase("-")) {
//          if (answerBuilder.length() == 0) {
//              answerBuilder.append(button);
//              answerView.setText(answerBuilder.toString());
//          }
//      } else {
//          answerBuilder.append(button);
//          answerView.setText(answerBuilder.toString());
//          // If click the button, then open feast app with the special event details
//          if (isAnswerCorrect()) {
//              alarmActive = false;
//              if (vibrator != null)
//                  vibrator.cancel();
//              try {
//                  mediaPlayer.stop();
//              } catch (IllegalStateException ise) {
//
//              }
//              try {
//                  mediaPlayer.release();
//              } catch (Exception e) {
//
//              }
//              this.finish();
//              // OPEN FEASTAPP event with those event details
//          }
//      }
//      if (answerView.getText().length() >= answerString.length()
//              && !isAnswerCorrect()) {
//          answerView.setTextColor(Color.RED);
//      } else {
//          answerView.setTextColor(Color.BLACK);
//      }
//      }
    }

    public boolean isAnswerCorrect() {
        //boolean correct = false;
        /*
        try {
            correct = mathProblem.getAnswer() == Float.parseFloat(answerBuilder
                    .toString());
        } catch (NumberFormatException e) {
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        */
        // So once click, it will be correct and close out the app
        boolean correct = true;
        return correct;
    }

    private void sendNotification(String msg) {
        Log.d("TAG", "Preparing to send notification...: " + msg);
        mNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, AlarmActivity.class), 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.abc_ic_clear_mtrl_alpha)
                .setContentTitle("GCM Notification")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        Log.d("TAG", "Notification sent successfully.");
    }

}

【问题讨论】:

  • 哪个警报对话框无限重复?是您的警报对话框吗?也许问题在于您在 AlarmAlertBroadcastReciever 中的代码?
  • @Karakuri 我已经更新了代码
  • @Karakuri,我已经更新了代码。有没有办法查看所有已创建警报的列表?
  • 无法查看安排了哪些警报,AlarmManager 不提供。到目前为止,我仍然没有看到任何产生警报对话框的代码,我的印象是问题可能出在该代码中。
  • @Karakuri 我添加了警报活动

标签: android crash alarmmanager infinite-loop


【解决方案1】:

在alarmalert活动中,在onClick我添加了:

Intent myIntent = new Intent(getApplicationContext(), AlarmAlertBroadcastReciever.class);
        myIntent.putExtra("alarm", Alarm.class);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);

取消闹钟

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2019-04-21
    相关资源
    最近更新 更多