Making a notification icon appear on boot/headset

2019-03-04 01:54发布

问题:

I want to make it so when one plugs in there headset a notification icon appears. I've made it so when the phone turns on this runs which starts the MainActivity class which has the code for the notification icon in the OnCreate method so it just automatically starts. The problem with that is that it starts the whole activity and app, which I don't want. I just want the icon to appear. How could I go about this? Thank You!

public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Intent myIntent = new Intent(context, MainActivity.class);
    myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(myIntent);
}

The above code starts the MainActivity on boot.

Notification Icon Code

    //Notification Icon Starts
    NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification=new Notification(R.drawable.icon_notification, "Icon Notification", System.currentTimeMillis());
    Context context=MainActivity.this;
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), Notification.FLAG_ONGOING_EVENT);        
    notification.flags = Notification.FLAG_ONGOING_EVENT;
    notification.setLatestEventInfo(this, "Notification Icon", "Touch for more options", contentIntent);
    Intent intent=new Intent(context,MainActivity.class);
    PendingIntent  pending=PendingIntent.getActivity(context, 0, intent, 0);
    nm.notify(0, notification);
    //Notification Icon Ends

回答1:

As I wrote in your last question, add a <receiver> in your manifest that listens for the ACTION_HEADSET_PLUG broadcast. The documentation shows Intent extras that you can use to find out if the headset is plugged in (state), etc.



回答2:

I posted a solution that allows you to monitor the headphone state (wired and bluetooth), over here. This solution could easily be extended to allow you to display a notification.