2016-02-26 68 views
0

執行。在我的Android清單我已經定義了一個BroadcastReceiver這樣的:的Android AlarmManager不會在當前時間

<receiver android:name="com.myexample.mycompany.countdownapp.MainActivity$WarningReceiver" 
      android:enabled="true"/> 

,然後在我的mainActivity我有一個WarningReceiver類。整個mainActivity非常小,看起來像這樣:

package com.myexample.mycompany.countdownapp; 

import android.app.AlarmManager; 
import android.app.PendingIntent; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.widget.Toast; 

import java.util.Calendar; 

public class MainActivity extends AppCompatActivity { 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     //10 seconds later 
     Calendar cal = Calendar.getInstance(); 
     cal.add(Calendar.SECOND, 0); 


     AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 

     Intent intent = new Intent(this, WarningReceiver.class); 
     PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); 

     alarmMgr.set(AlarmManager.ELAPSED_REALTIME, 
       cal.getTimeInMillis(), alarmIntent); 

    } 




    public static class WarningReceiver extends BroadcastReceiver { 

     public Void sendWarningEvent() throws Exception { 
      // fire off warning event 
      Log.v("WarningReceiver", "sendWarningEvent called from WarningReceiver"); 
      return null; 
     } 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      try { 

       Toast.makeText(context, 
         "WarningReceiver.onReceive()", 
         Toast.LENGTH_LONG).show(); 

       sendWarningEvent(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

當我運行應用程序沒有被觸發。我究竟做錯了什麼 ?

+1

日曆讓你有時間的RTC。當前配置中的警報管理器預計ELAPSED_REALTIME。更改參數。 –

+0

ELAPSED_REALTIME - SystemClock.elapsedRealtime()中的鬧鐘時間(自啓動以來的時間,包括睡眠時間)。不知道你得到了你想要的。 –

回答

3

試試這個:而不是

alarmMgr.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), alarmIntent); 

alarmMgr.set(AlarmManager.ELAPSED_REALTIME,cal.getTimeInMillis(), alarmIntent);