我想在插入耳機後顯示通知,並在拔出插頭後將其隱藏。因此我在BOOT_COMPLETED觸發的BroadCastReceiver中註冊了ACTION_HEADSET_PLUG Intent Listener。在我的情況下,我使用HTC Sense(HTC One S),並且只有在Sense加載(WaitDialog)後插入耳機時纔會顯示該通知,之後該通知不再顯示。已註冊ACTION_HEADSET_PLUG監聽器只觸發幾次
如果我通過'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);
}
HeadsetStateReceiver:
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();
}
}
xml-stuff不起作用,因爲Intent被廣播爲「僅註冊」。使用BootCompletedListener是因爲我想獨立於App本身運行Notification本身。 – bluewhile 2012-07-16 13:17:19
檢查:http://commonsware.com/blog/2011/07/13/boot-completed-regression-confirmed.html也許這是一個問題。一般來說,廣播接收機的清單和手動註冊之間沒有區別 – 2012-07-16 13:25:45
不完全是:用戶打開我的應用程序。然後,應用程序完成其工作,最後通過su重新啓動設備。然後,BOOT_COMPLETED Intent被捕獲,但由於某些原因,它檢測到一個或兩個耳機交互,然後停止。 – bluewhile 2012-07-16 13:29:14