AlarmManager提供了一種系統級的提示服務,允許你安排在將來的某個時間執行一個服務。AlarmManager對象一般通過Context.getSystemService(Context.ALARM_SERVICE)方法獲得。
下面看一個例子加深理解:<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ=="brush:java;">package com.app;import com.app.R;import android.app.Activity;import android.app.AlarmManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;/** * * 測試AlarmManager */public class MainActivity extends Activity {// 聲明Buttonprivate Button setBtn, cancelBtn;// 定義廣播Actionprivate static final String BC_ACTION = "com.action.BC_ACTION";@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 設定當前布局視圖setContentView(R.layout.main);// 執行個體化ButtonsetBtn = (Button) findViewById(R.id.Button01);cancelBtn = (Button) findViewById(R.id.Button02);// 獲得AlarmManager執行個體final AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);// 執行個體化IntentIntent intent = new Intent();// 設定Intent action屬性intent.setAction(BC_ACTION);intent.putExtra("msg", "你該去開會啦!");// 執行個體化PendingIntentfinal PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0,intent, 0);// 獲得系統時間final long time = System.currentTimeMillis();// 設定按鈕單擊事件setBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 重複提示,從目前時間開始,間隔5秒am.setRepeating(AlarmManager.RTC_WAKEUP, time,5 * 1000, pi);}});// 設定按鈕單擊事件cancelBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {am.cancel(pi);}});}}
註:PendingIntent的一個靜態方法,
getBroadcast
public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags)
Retrieve a PendingIntent that will perform a broadcast, like calling
Context.sendBroadcast().
參數:
context - The Context in which this PendingIntent should perform the broadcast.
requestCode - Private request code for the sender (currently not used).
intent - The Intent to be broadcast.
flags - May be
FLAG_ONE_SHOT,
FLAG_NO_CREATE,
FLAG_CANCEL_CURRENT,
FLAG_UPDATE_CURRENT, or any of the flags as supported by
Intent.fillIn() to control which unspecified parts of the intent that can be supplied when the actual send happens.
返回:Returns an existing or new PendingIntent matching the given parameters. May return null only if
FLAG_NO_CREATE has been supplied.
package com.app;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class MyReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {// 獲得提示資訊String msg = intent.getStringExtra("msg");// 顯示提示資訊Toast.makeText(context, msg, Toast.LENGTH_LONG).show();}}
別忘了在AndroidManifest.xml中註冊MyReceiver:
結果: