2015-06-27 68 views
0

報警的日期和時間,並單獨創建,然後設置一個報警爲:報警重複無限 - 鎖定了電話

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(日曆alarmTime){ this.alarmTime = 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); 
    } 

} 

AlarmService類:

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; 
    } 

} 

AlarmAlertAc tivity:

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."); 
    } 

} 
+0

?它是你的警報對話框嗎?也許問題在於AlarmAlertBroadcastReciever中的代碼? – Karakuri

+0

@Karakuri我已更新代碼 – Sauron

+0

@Karakuri,我已更新代碼。有沒有辦法查看所有創建的警報列表? – Sauron

回答

0

在報警警報活動,在我的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); 

要取消它是無限重複的警告對話框報警