1. 程式人生 > >Android定時器AlarmManager(定時傳送廣播)

Android定時器AlarmManager(定時傳送廣播)

參考

1、MainActivity.java

AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();

calendar.setTimeInMillis(System.currentTimeMillis());

calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));

calendar.add(Calendar.SECOND, 1);

Intent intent =new Intent(

"intent_alarm_log");

PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this,  0,intent,  0);  

long intervalMillis  = 3000;// 3秒,此設定無用,時間間隔誤差60s

am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),intervalMillis,sender); 

Toast.makeText(MainActivity.this, "設定簡單鬧鈴成功!", Toast.LENGTH_LONG

).show();

2、接收廣播AlarmReceiver.java

public class AlarmReceiverextends BroadcastReceiver {

@Override

    public void onReceive(Contextcontext, Intentintent) {

String action = intent.getAction();

if (action =="intent_alarm_log") {

            Log.d("alarm_receive","鬧鈴響了, 可以做點事情了~~");

        }

    }

}

3、AndroidManifest.xml

<receiverandroid:name=".AlarmReceiver">

<intent-filter>

<actionandroid:name="intent_alarm_log"/>

</intent-filter>

</receiver>