使用AlarmManager

来源:互联网 发布:单片机测量交流电压 编辑:程序博客网 时间:2024/06/05 03:59

1.1使用PendingIntent包装一个Intent,用以将来执行某一任务
1.2获取AlarmManage对象并使用set(int type, long triggerAtMillis, PendingIntent operation)方法设定执行时间
1.2.1 如果type为“RTC”或“RTC_WAKEUP”,Alarm time 根据 System.currentTimeMillis(),自January 1, 1970 00:00:00.0 UTC计算,单位是毫秒
1.2.1 如果type为“ELAPSED_REALTIME”或“ELAPSED_REALTIME_WAKEUP”,Alarm time 根据 SystemClock.elapsedRealtime(),自系统开机时间计算,单位是毫秒
1.2.1 有“WAKE_UP”表示会唤醒系统,没有的表示会在下次系统被唤醒时执行

//闹钟设定时间到时要执行CallAlarm.classIntent intent  = new Intent(MainActivity.this,CallAlarm.class);intent.setAction("STOP");PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this,1, intent, PendingIntent.FLAG_UPDATE_CURRENT);//获取AlarmManager//AlarmManager.RTC设定服务不唤醒设备,在下次设备唤醒时执行AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);//set()设定的PendingIntent只会执行一次am.set(AlarmManager.RTC, System.currentTimeMillis()+5*1000,sender);

2.使用一个类实现onReceive(…)方法

public class CallAlarm extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        Toast.makeText(context,"5 Seconds", Toast.LENGTH_LONG).show();    }}

3.在AndroidMainfest注册

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.gs.lf.alarmclock" >    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name"            android:theme="@style/AppTheme.NoActionBar" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <receiver            android:name=".CallAlarm">            <intent-filter>                <action android:name="STOP" />            </intent-filter>        </receiver>    </application></manifest>
0 0
原创粉丝点击