我希望在闹钟触发时通知用户。但它不会通知。我不知道为什么。我尝试了其他来源,但它根本没有帮助。
这是我的代码:
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent3 = new Intent(context, ViewTasksActivity.class);
PendingIntent pIntent3 = PendingIntent.getActivity(context, 0, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
//assigned a unique id to notifications
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
Notification mNotification = new Notification.Builder(context)
.setContentTitle("Testing Notifications")
.setContentText("")
.setSubText("Complete the tasks under this activity.")
.setSmallIcon(R.drawable.gsoicon)
.setContentIntent(pIntent3)
.setSound(soundUri)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// If you want to hide the notification after it was selected, do the code below
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(m, mNotification);
}
我已将它放在清单文件中:
<receiver android:name='com.goalsettingorganizer.AlarmManagerBroadcastReceiver'>
</receiver>
设置闹钟代码:
public void SetAlarms(Context context, int goal_id)
{
dbhandler = new MyDBAdapter(context);
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
List<Activities> allActs = dbhandler.getAllActivitiesByGoal(goal_id);
for (final Activities act : allActs) {
//for alarm
//Create an offset from the current time in which the alarm will go off.
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.DATE, Integer.parseInt(act.getEDay())); //1-31
cal.set(Calendar.MONTH, Integer.parseInt(act.getEMonth()) - 1); //first month is 0!!! January is zero!!!
cal.set(Calendar.YEAR, Integer.parseInt(act.getEYear()));//year...
cal.set(Calendar.HOUR_OF_DAY, act.getHour());
cal.set(Calendar.MINUTE, act.getMinute());
cal.set(Calendar.SECOND, act.getSecond());
cal.set(Calendar.MILLISECOND, act.getMillisecond());
//Create a new PendingIntent and add it to the AlarmManager
Intent intent3 = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent3.putExtra("goalid", Integer.toString(goal_id));
intent3.putExtra("activityId", Integer.toString(act.getActId()));
intent3.putExtra("activityName", act.getActivityName());
intent3.putExtra("show", "true");
PendingIntent pendingIntent = PendingIntent.getActivity(context,
act.getActId(), intent3, PendingIntent.FLAG_CANCEL_CURRENT);
if (Build.VERSION.SDK_INT >= 19)
am.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
else
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}
}
我的错误:
我把getActivity()放在PendingIntent而不是getBroadcast()中。这就是OnReceive无法运作的原因。