【发布时间】:2011-10-09 13:51:19
【问题描述】:
我正在尝试从广播接收器启动状态栏通知,然后从另一个广播接收器停止它,但我遇到了问题。我想在连接 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);
}
}
【问题讨论】:
标签: java android notifications broadcastreceiver statusbar