我正在尝试在特定时间发送通知,该部分工作正常,但是在重新启动电话后,除非打开应用程序然后启动服务,否则该服务将无法启动。我已经在线尝试了多种解决方案,但仍然无法解决问题。
活动:
private void startNotificationAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, ReminderBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), intent, 0);
Objects.requireNonNull(alarmManager).setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
BroadcastReceiver
:
public class ReminderBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, BootService.class);
intent.setAction("<package>.Receiver");
context.startService(serviceIntent);
} else {
scheduleNotification(context, intent);
}
}
private void scheduleNotification(Context context, Intent intent) {
Notification notification = new NotificationCompat.Builder(context, BaseApp.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_calendar_alert)
.setContentTitle(title)
.setContentText(message)
.setColor(color)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Objects.requireNonNull(notificationManager).notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);
}
IntentService
:
public class BootService extends IntentService {
public BootService() {
super("BootService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
try {
Thread.sleep(5000);
startNotification();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Manifest
<receiver
android:name=".Receiver.ReminderBroadcastReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service android:name=".Service.BootService"/>
答案 0 :(得分:0)
您必须在清单中提供以下权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
此外,您还必须将android:exported
设为true
根据android文档:
android:exported
广播接收器是否可以从其应用程序外部的源接收消息-如果可以,则为“ true”,并且 如果不是,则为“ false”。如果为“ false”,则仅广播接收方消息 可以接收的是由同一应用程序的组件发送的那些,或者 具有相同用户ID的应用程序。
示例代码
<receiver android:name=".sample.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>