我一直在寻找3天。我在谷歌和 stackoverflow.com 中尝试了所有解决方案。
我有MainActivity
这样开始BroadcastReceiver
。
Calendar calendar3 = Calendar.getInstance();
calendar3.set(Calendar.HOUR_OF_DAY, 7);
calendar3.set(Calendar.MINUTE, 34);
calendar3.set(Calendar.SECOND, 00);
Intent intent = new Intent(MainAcitivty.this, BroadCastReciver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainAcitivty.this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar3.getTimeInMillis(), pendingIntent);
我也试过alarmManager.setReapeating
而没有运气。
然后BroadcastReceiver
启动service
,它从db获取一些信息并将其放入notification
或更多这样的内容:
Intent i = new Intent(context,MyService.class);
context.startService(i);
服务
public class MyService extends Service {
MyDB db;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Yamen", "service Started");
db = new MyDB(getApplicationContext());
GregorianCalendar calendar = new GregorianCalendar();
Date time = calendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
String timeString = simpleDateFormat.format(time);
SharedPreferences mySharedPreferences = getApplicationContext().getSharedPreferences("myPref",Context.MODE_PRIVATE);
boolean isNoti=mySharedPreferences.getBoolean("isNoti",true);
if (isNoti) {
ArrayList<AnniBean> annis =
db.getAnni(timeString);
Log.e("Yamen", "size is " + annis.size());
for (AnniBean anni : annis) {
new NotificationCreator(getApplicationContext(), "Anniversary Reminder", anni.getAnniName(), anni.getAnniDetails());
}
}
Log.e("Yamen", "service finished");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
每天早上7:34出现{p> notification
就像一个魅力。问题是每次打开应用程序时都会调用BroadcastReceiver
和service
。
请不要将我推荐给任何链接,因为我确实访问了很多这方面的链接。 谢谢你的建议
答案 0 :(得分:0)
问题在于广播接收器意图XML。它接收其他广播,你应该按照这样的动作过滤: 在Java中:
Intent intent = new Intent(MainAcitivty.this, BroadCastReciver.class);
intent.setAction("your.package.name.your.anything");
XML中的:
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="your.package.name.your.anything" />
</intent-filter>
</receiver>
答案 1 :(得分:0)
尝试使用以下代码:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 7);
cal.set(Calendar.MINUTE, 34);
cal.set(Calendar.SECOND, 0);
if(cal.before(Calendar.getInstance())){ // if it's in the past, increment
cal.add(Calendar.DATE, 1);
}
Intent intent = new Intent(MainAcitivty.this, BroadCastReciver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainAcitivty.this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
此警报将在指定时间每天运行。