Hellow。 我开发的应用程序需要在用户24小时不使用应用程序时显示本地通知。
我的代码:
MainActivity
@Override
protected void onDestroy() {
super.onDestroy();
Calendar calendar = Calendar.getInstance();
Intent myIntent = new Intent(MainActivity.this, ReminderReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), getInterval(), pendingIntent);
}
private int getInterval() {
int hours = 24;
int minutes = 60;
int seconds = 60;
int milliseconds = 1000;
return hours * minutes * seconds * milliseconds;
}
ReminderReceiver
public class ReminderReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, ReminderService.class);
context.startService(service1);
}
}
ReminderService
public class ReminderService extends Service {
private static final int NOTIFICATION_ID = 1;
private NotificationManager notificationManager;
private PendingIntent pendingIntent;
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Context context = this.getApplicationContext();
notificationManager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this, MainActivity.class);
pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Get Your PSN Code for FREE Now!");
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentIntent(pendingIntent);
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
但它不能正常工作,当我关闭应用程序时会立即显示通知。我理解这是因为我给出了初始时间calendar.getTimeInMillis()
,但我不知道其他的。
怎么做对了?
感谢。
答案 0 :(得分:0)
它帮助了我
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pendingIntent);