ヘッドセットが接続された後に通知を表示し、プラグを抜いた後に非表示にしたい。したがって、BOOT_COMPLETED でトリガーされる BroadCastReceiver に ACTION_HEADSET_PLUG インテント リスナーを登録します。私の場合、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>
...
OnBootReceiver:
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();
}
}