我正在使用AlarmManager在特定时间启动服务,该服务应在调用时发送通知。但是当应用程序在后台被终止或停止时,似乎AlarmManager不起作用。
我的代码: (MainActivity)
public void setMobile(String mob) {
mobile = mob.chars().allMatch(Character::isDigit)? mob : mobile;
}
服务:
Intent iNotifikace = new Intent(context, Notifikace.class);
PendingIntent notifikace = PendingIntent.getBroadcast(this, 0, iNotifikace, 0);
alarmMgr = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time));
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, notifikace);
BootReceiver:
public class Notifikace extends IntentService {
public Notifikace() {
super("Notifikace");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
}@Override
public int onStartCommand(Intent intent, int flags, int startId) {
HandlerThread thread = new HandlerThread("Thread Name");
Intent i = new Intent(context, Notifikace.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notification")
.setContentText("NotificationText");
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(002, mBuilder.build()); stopSelf();
return START_NOT_STICKY;
}}
public class BootReceiver extends BroadcastReceiver {
private AlarmManager alarmMgr;
private SharedPreferences sharedPref;
@Override
public void onReceive(Context context, Intent intent) {
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String time = sharedPref.getString("pref_time", "16");
Intent iNotifikace = new Intent(context, Notifikace.class);
PendingIntent notifikace = PendingIntent.getService(context, 0, iNotifikace, 0);
alarmMgr = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time));
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, kontrolaZastupovani);
}}
<?xml version="1.0" encoding="utf-8"?>
感谢您的帮助,祝您度过愉快的一天!