我正在开发一个应用程序,其中我需要根据用户选择的间隔显示通知。即使应用已关闭,我也必须显示这些通知。我已经使用AlarmManager来安排重复通知。当应用程序正在运行或尝试时,它运行正常,但如果应用程序被杀死,则无法正常工作。
public static void setRecurringNotification(Context context, long scTime) {
System.out.println("Inside setRecurringNotification()");
Intent notificationIntent = new Intent(context,
NotificationReceiver.class);
pendingIntentNotification = PendingIntent.getBroadcast(context, 0,
notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
SystemClock.elapsedRealtime() + scTime, scTime,
pendingIntentNotification);
}// End of setRecurringAlarm()
以下是NotificationReceiver类:
public class NotificationReceiver extends WakefulBroadcastReceiver {
public static void sendNotification(Context context, MyMessage msg) {
System.out.println("sendNotification(): " + msg.getId());
Uri soundUri = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(msg.getTitle())
.setSmallIcon(R.drawable.ic_launcher)
.setStyle(
new NotificationCompat.BigTextStyle().bigText(msg.getContent()))
.setContentText(msg.getContent())
.setSound(soundUri);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(1, mBuilder.build());
}// End of sendNotification
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Inside NotificationReceiver.onReceive...");
try {
new NotifyUser(context).execute();
}
catch (Exception ex) {
ex.printStackTrace();
}
setResultCode(Activity.RESULT_OK);
}
private class NotifyUser extends AsyncTask<Void, Void, String> {
private Context context;
public NotifyUser(Context context) {
this.context = context;
}
@Override
protected String doInBackground(Void... params) {
SQLHelper sqlHelper = new SQLHelper(context);
try {
MyMessage msg = sqlHelper.getRandomMyMessageFromDB();
if (null != msg)
sendNotification(context, msg);
}
catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
}