首先你需要使用广播接收器。并且因为广播接收器只启动很短的时间
来自 android 开发者博客。处理广播时,应用程序会被赋予一组固定的时间(当前为 10 秒)来完成其工作。如果它没有在这段时间内完成,应用程序将被视为行为不当,并且其进程会立即进入后台状态,以便在需要时被杀死以获取内存。
使用意向服务是一种更好的做法,这里有一个如何做到这一点的示例。
这是广播接收器类。
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, MyNewIntentService.class);
context.startService(intent1);
}
}
并将其注册到清单中。
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="false" >
</receiver>
这是意图服务类。
public class MyNewIntentService extends IntentService {
private static final int NOTIFICATION_ID = 3;
public MyNewIntentService() {
super("MyNewIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("My Title");
builder.setContentText("This is the Body");
builder.setSmallIcon(R.drawable.whatever);
Intent notifyIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 2, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//to be able to launch your activity from the notification
builder.setContentIntent(pendingIntent);
Notification notificationCompat = builder.build();
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(NOTIFICATION_ID, notificationCompat);
}
}
并将其注册到清单中。
<service
android:name=".MyNewIntentService"
android:exported="false" >
</service>
然后在您的活动中设置闹钟管理器以在特定时间启动广播接收器,并使用 AlarmManager setRepeating 方法重复它,下面的示例将每天重复它。
Intent notifyIntent = new Intent(this,MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast
(context, NOTIFICATION_REMINDER_NIGHT, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1000 * 60 * 60 * 24, pendingIntent);
我希望这能帮到您。