我希望我的应用每天都会在特定时间显示通知。为此,我将以下代码放在我的MainActivity类的onCreate方法中(默认情况下在应用程序启动时打开)。
Mainactivity.class
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setNotification(Mainactivity.this);
}
public void setNotification(Context context) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,12);
calendar.set(Calendar.MINUTE,1);
calendar.set(Calendar.SECOND,0);
long c = System.currentTimeMillis();
long t = calendar.getTimeInMillis();
if (t <= c) {
calendar.add(Calendar.DATE, 1);
}
Intent intent = new Intent(this, NotificationReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 100, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager,RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
boolean alarmUp = (PendingIntent.getBroadcast(MainActivity.this, 100,
new Intent(this, NotificationReciever.class),
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp) {
Toast.makeText(MainActivity.this,"Aan",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,"Niet aan",Toast.LENGTH_SHORT).show();
}
}
然后在NotificationReceiver类中,我只是构造并启动通知。它在正确的时间执行此操作,但也始终在应用程序启动时执行此操作。我不知道如何阻止通知在应用程序启动时停止启动,有人可以帮助我吗?
我尝试过的一件事是检查当前时间是否大于或等于应该启动通知的时间。我通过在NotificationReceiver类中实现以下代码来实现这一点:
NotificationReceiver.class
public class NotificationReciever extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
Intent new_intent = new Intent(context, MainActivity.class);
new_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, new_intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_stat_name)
.setTicker("ticker_title")
.setContentTitle("content_title")
.setContentText("description")
.setAutoCancel(true);
notificationManager.notify(0, notification.build());
MainActivity mainActivity = new MainActivity();
mainActivity.setNotification(context);
}
}
但是,这种方式通知在以前启动应用程序之前不会启动,在本例中为12:01,但在此时间之后仍然会启动...(顺便说一句,以下代码已添加到我的清单中)< / p>
<receiver android:name=".NotificationReciever"/>
答案 0 :(得分:0)
您应该使用service job来安排任务
答案 1 :(得分:0)
使用Firebase Job Dispatcher,您也可以使用JobScheduler,但Firebase Job Dispatcher非常简单。休息你的选择。