这可能已经晚了,但我希望它能对某人有所帮助。
我在同一个问题上停留了很长时间。但是现在我知道如何解决这个问题。这适用于可能有相同问题的任何人。人们一直在说您必须启用自动启动功能,但是我设法使用了自动启动功能。
首先,现在不赞成使用WakeFullBroadcastaReceiver,您应该使用BroadcastReceiver。其次,您必须使用ForegroudService而不是BackgroundService。
我将在下面为您提供示例:
IntentService.class
public class NotificationService extends IntentService {
public NotificationService() {
super("NotificationService");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY;
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
startForegroundServiceT();
sendNotification(intent);
stopSelf();
}
private void startForegroundServiceT(){
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build();
startForeground(1, notification);
}
}
private void sendNotification(Intent intent){
}
}
在BroadcastReceiver.class中启动前台服务
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, NotificationService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(service);
} else {
context.startService(service);
}
}
}
而setAlarms像这样:
public static void setAlarm(Context context, int requestCode, int hour, int minute){
AlarmManager alarmManager =( AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context
, AlarmReceiver.class);
intent.setAction("android.intent.action.NOTIFY");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1001, intent, 0);
Calendar time = getTime(hour, minute);
if (Build.VERSION.SDK_INT >= 23){
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,time.getTimeInMillis(),pendingIntent);
}
else{
alarmManager.set(AlarmManager.RTC_WAKEUP,time.getTimeInMillis(),pendingIntent);
}
然后,您必须在清单中声明接收方和前台服务。
<receiver android:name=".AlarmReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.NOTIFY">
</action>
</intent-filter>
</receiver>
<service
android:name=".NotificationService"
android:enabled="true"
android:exported="true"></service>
我希望这可以帮助别人。