2016-12-23 216 views
1

我寫的代碼在我的MainActivity的重複報警,每當我開始我的應用程序重複報警我everytime.But希望它每隔24小時後重複重複報警每一天

MainActivity.java

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_home); 
    sessionManager = new SessionManager(this); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    toolbar.setBackgroundColor(getResources().getColor(R.color.black)); 
    setSupportActionBar(toolbar); 
    repeatAlarm(); 
    } 


    private void repeatAlarm() { 
    Date when = new Date(System.currentTimeMillis()); 
    try { 
     Intent someIntent = new Intent(getApplicationContext(), MyReciever.class); // intent to be launched 
     // note this could be getActivity if you want to launch an activity 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, // id, optional 
       someIntent, // intent to launch 
       PendingIntent.FLAG_CANCEL_CURRENT); // PendintIntent flag 
     AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
     alarms.setRepeating(AlarmManager.RTC_WAKEUP, when.getTime(), AlarmManager.INTERVAL_DAY, pendingIntent); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

這就像您編寫代碼一樣工作。你應該檢查你是否設置了警報,然後不要再設置警報。而且我可以看到給予小時的間隔時間,而不是到達天。 –

+0

除了重新啓動後還需要考慮設置鬧鐘。也打擾限制https://developer.android.com/training/monitoring-device-state/doze-standby.html – Raghunandan

回答

1

使用PendingIntent.getService

PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, // id, optional 
      someIntent, // intent to launch 
      PendingIntent.FLAG_CANCEL_CURRENT); 

,而不是PendingIntent.getBroadcast

PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, // id, optional 
      someIntent, // intent to launch 
      PendingIntent.FLAG_CANCEL_CURRENT); 

更多詳細信息請參考Here