请尝试以下操作:
不过,首先让我们定义一个广播接收器,它将由闹钟执行,并启动我们的IntentService:
public class MyAlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
public static final String ACTION = "com.codepath.example.servicesdemo.alarm";
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyTestService.class);
i.putExtra("foo", "bar");
context.startService(i);
}
}
接下来,让我们在AndroidManifest.xml中注册我们的IntentService和MyAlarmReceiver。
<receiver
android:name=".MyAlarmReceiver"
android:process=":remote" >
</receiver>
<service
android:name=".MyTestService"
android:exported="false" />
Java活动
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleAlarm();
}
public void scheduleAlarm() {
Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this,
MyAlarmReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
long firstMillis = System.currentTimeMillis();
AlarmManager alarm = (AlarmManager)
this.getSystemService(Context.ALARM_SERVICE);
RTC_WAKEUP
INTERVAL_HOUR, INTERVAL_DAY
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
AlarmManager.INTERVAL_HALF_HOUR, pIntent);
}
}
设置完闹钟后,如果我们想要取消闹钟,可以这样做:
public void cancelAlarm() {
Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pIntent);
}
并检查您的清单权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
我不确定,但请检查一下,也许可以帮助你