-1
Hellow。 我開發的應用程序需要在用戶不使用應用程序24小時時顯示本地通知。當用戶不使用應用程序時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()
,但我不知道怎麼回事。
如何做到這一點的權利?
謝謝。
嘗試[這一個](https://stackoverflow.com/a/35127736/5860777)可能是這個幫助你。你需要改變這段代碼的時間,我希望這會幫助你。 –
@安迪開發者我不明白如何改變這一點。也許我需要在日曆中設置當前時間,例如,減去1分鐘,以便警告不會立即顯示。但我不知道如何設置日期減去1分鐘。 –
你可以[試試這個](https://stackoverflow.com/a/625624/5860777)將currentmillis轉換爲小時,分鐘和秒。當你得到這只是傳遞給Calendar.HOUR_OF_DAY,Calendar.MINUTE和Calendar.SECOND。 –