我想在插入耳机后显示通知,并在拔下耳机后隐藏它。因此,我在一个在 BOOT_COMPLETED 触发的 BroadCastReceiver 中注册了 ACTION_HEADSET_PLUG Intent Listener。在我的情况下,我使用 HTC Sense (HTC One S),并且只有在 Sense 正在加载 (WaitDialog) 时插入耳机时才会显示通知,之后它将不再显示。
如果我在运行时通过“new OnBootreceiver().onReceive(this, null)”触发应用程序中的 OnBootListener,它会完美运行。
显现:
...
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
...
</activity>
<receiver android:name=".OnBootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
...
OnBoot接收器:
public void onReceive(Context context, Intent intent) {
IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
HeadsetStateReceiver receiver = new HeadsetStateReceiver();
context.registerReceiver( receiver, receiverFilter );
}
耳机状态接收器:
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,
"" + (Integer) (intent.getExtras().get("state")),
Toast.LENGTH_SHORT).show();
mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Log.e(this.getClass().toString(), "Intent Headset_plug received "
+ intent);
if ((Integer) (intent.getExtras().get("state")) != 0) {
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.contentIntent = PendingIntent.getActivity(
context.getApplicationContext(), 0, new Intent(), 0);
notification.setLatestEventInfo(context, title, message,
notification.contentIntent);
mNotificationManager.notify(0xBEA15, notification);
} else {
mNotificationManager.cancelAll();
}
}