我正在尝试从广播接收器启动状态栏通知,然后从另一个广播接收器停止它,但我遇到了问题。当 USB 连接时,我想在状态栏中启动通知,然后当 USB 断开连接时,我想停止它。我已经设置好了两个接收器并且可以正常工作,只是在从接收器启动和停止通知方面遇到了困难。以下是我目前的代码。
我的代码唯一的错误是
我的代码唯一的错误是
myNotificationManager = (NotificationManager) getSystemService(context.NOTIFICATION_SERVICE);
这一行,错误提示为getSystemService未定义,并且它想要创建该方法,我猜这意味着接收器不支持像活动那样的该方法,那么我应该怎么做才能从接收器中创建和停止通知呢?感谢您的帮助。public class USBConnect extends BroadcastReceiver {
public NotificationManager myNotificationManager;
public static final int NOTIFICATION_ID = 1;
@Override
public void onReceive(Context context, Intent intent) {
myNotificationManager = (NotificationManager) getSystemService(context.NOTIFICATION_SERVICE);
CharSequence NotificationTicket = "USB Connected!";
CharSequence NotificationTitle = "USB Connected!";
CharSequence NotificationContent = "USB is Connected!";
Notification notification = new Notification(R.drawable.usbicon, NotificationTicket, 0);
Intent notificationIntent = new Intent(context, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, NotificationTitle, NotificationContent, contentIntent);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
myNotificationManager.notify(NOTIFICATION_ID, notification);
}
}
然后当接收器断开连接时,我认为这个部分是正常的,并且应该可以工作。我认为我的问题仅存在于USBConnect类中。
public class USBDisCon extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(USBConnect.NOTIFICATION_ID);
}
}