我想显示通知并在每个时段重复一次。我读了如何制作它,并在扩展广播接收器的类中制作了代码:
public class OnAlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence tickerText = "Votre vidange approche";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
CharSequence contentTitle = "Notification";
CharSequence contentText = "Vérifier votre kilométrage";
Intent notificationIntent = new Intent(this, Acceuil.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
}
但是,我不知道为什么会出现这种错误:
The method getSystemService(String) is undefined for the type OnAlarmReceiverThe constructor Intent(OnAlarmReceiver, Class<Acceuil>) is undefined
The method getActivity(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (OnAlarmReceiver, int, Intent, int)
在其他活动中我猜我必须这样做:
public void notifs() {
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1800000, pi);
}
这里有什么问题? 非常感谢你。
答案 0 :(得分:3)
区别在于:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
和
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
第二个可以工作,因为你在一个应用程序上下文中调用getSystemService,就像你在第一个尝试在这个对象上调用它一样,此时该对象是BroadcastReceiver的子类实例,它没有名为getSystemService的方法。 / p>
要解决此问题,请执行以下操作:
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
这一行给你带来了问题,因为你试图将自定义类的一个实例作为this对象而不是像它期望的那样传递Context对象。
要解决此问题,请执行以下操作:
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);