本程序执行效果为:
隔3秒打印"收到广播"
隔3秒打印"收到广播"
package com.example.timingtest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("收到广播");
}
}
package com.example.timingtest;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar c=Calendar.getInstance();
Intent intent=new Intent(this,AlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(this, 0, intent,0);
//设置一个PendingIntent对象,发送广播
AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
//获取AlarmManager对象
am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
//时间到时,执行PendingIntent,只执行一次
//AlarmManager.RTC_WAKEUP休眠时会运行,如果是AlarmManager.RTC,在休眠时不会运行
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 3000, pi);
//如果需要重复执行,使用上面一行的setRepeating方法,倒数第二参数为间隔时间,单位为毫秒
}
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.timingtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" android:process=".abc"/>
</application>
</manifest>