[英]Call Notification from BroadcastReceiver
I have the code : 我有代码:
public void AlarmStart() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 5);
Intent intent = new Intent(MainNote.this, AlarmReceiver.class);
intent.putExtra("alarm_message", "MESS");
PendingIntent sender = PendingIntent.getBroadcast(MainNote.this, 1,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
}
It calls AlarmReceiver class on time. 它按时调用AlarmReceiver类。
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String message = bundle.getString("alarm_message");
NotifierHelper.sendNotification(?????, MainNote.class, "ba", "baba",
2, true, true);
} // Problem here
}
Then NotifierHelper class: 然后是NotifierHelper类:
public class NotifierHelper {
private static final int NOTIFY_1 = 0x1001;
public static void sendNotification(Activity caller,
Class<?> activityToLaunch, String title, String msg,
int numberOfEvents, boolean flashLed, boolean vibrate) {
NotificationManager notifier = (NotificationManager) caller
.getSystemService(Context.NOTIFICATION_SERVICE);
final Notification notify = new Notification(R.drawable.icon, "",
System.currentTimeMillis());
notify.icon = R.drawable.icon;
notify.tickerText = "New Alerts";
notify.when = System.currentTimeMillis();
notify.number = numberOfEvents;
notify.flags |= Notification.FLAG_AUTO_CANCEL;
if (flashLed) {
// add lights
notify.flags |= Notification.FLAG_SHOW_LIGHTS;
notify.ledARGB = Color.CYAN;
notify.ledOnMS = 500;
notify.ledOffMS = 500;
}
if (vibrate) {
notify.vibrate = new long[] { 100, 200, 200, 200, 200, 200, 1000,
200, 200, 200, 1000, 200 };
}
Intent toLaunch = new Intent(caller, activityToLaunch);
PendingIntent intentBack = PendingIntent.getActivity(caller, 0,
toLaunch, 0);
notify.setLatestEventInfo(caller, title, msg, intentBack);
notifier.notify(NOTIFY_1, notify);
}
}
How can I pass Activity caller
from AlarmReceiver? 如何从AlarmReceiver传递
Activity caller
?
I think that you don't need any reference to an Activity in the NotifierHelper. 我认为您在NotifierHelper中不需要任何对Activity的引用。 Use the Context (which Activity is a subclass of), eg:
使用上下文(Activity是其子类),例如:
public static void sendNotification(Context caller, ...
Such methods as getSystemService(), etc.. are actually exposed by Context. 诸如getSystemService()之类的方法实际上是由Context公开的。
And since you get passed a Context in AlarmReceiver.onReceive(), you can pass it on. 并且由于您在AlarmReceiver.onReceive()中传递了上下文,因此可以继续传递它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.