我想这样做,当一个人插入耳机时,在手机上做任何事情时,不仅仅是在应用程序上开始,通知图标出现在通知区域(非常顶部)我已经有了通知图标代码
//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
现在我只需要它,所以当您插入耳机时会显示。所以我用这个创建了一个新类,它检测它是否插入,然后记录它。这一切都有效
public class MusicIntentReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.d("unplugged", "Headset was unplugged");
break;
case 1:
Log.d("plugged", "Headset is plugged");
break;
default:
Log.d("uh", "I have no idea what the headset state is");
}
}
}
所以我所做的就是尝试将通知图标代码放在案例 1 中,这样当它检测到它已插入时,它就会运行它。但事实并非如此,而是我得到了大量的错误。这是一个截图http://prntscr.com/1xblhb 我只是想不出任何其他方法来解决这个问题,我已经坚持了这么久。因此,如果您能帮助我并尝试用初学者的方式说出来,那对我来说就意味着整个世界。太感谢了。