I am trying to start a status bar notification from a broadcast receiver and then stop it from another broadcast receiver, but I am having problems. I would like to start a notification in the status bar when usb is connected, and then when usb is disconnected, I would like to stop it. I have two receivers installed and it works, just struggling with starting and stopping one of the receiver, here is the code I have
My only mistake with my code is the line myNotificationManager = (NotificationManager) getSystemService(context.NOTIFICATION_SERVICE); , in which the error only says that getSystemService is undefined, and he wants to make a method which, I believe, means that the recipient does not have support for this method, such as activity, so what should I do to create and stop the notification from recipients, thanks for any help.
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); } }
And then the receiver, when it turns it off, I think is good and should work. I think my problem is only in the USBConnect class
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); } }
user577732
source share