我试过这些手机:摩托罗拉 Backflip 1.5、Nexus One 2.1
基本上我注册 BroadcastReceiver 以获得 ACTION_HEADSET_PLUG 广播并查看 3 个额外的意图:
- 状态
- 姓名
- 麦克风
以下是 API 的描述:
* state - 0 for unplugged, 1 for plugged.
* name - Headset type, human readable string
* microphone - 1 if headset has a microphone, 0 otherwise
问题#1:广播在活动开始(非预期)、屏幕旋转发生(非预期)以及耳机/耳机插入/拔出(预期)时出现。
问题 #2:后空翻手机 (1.5) 为状态 + 麦克风发送 null,当耳机/耳机拔出时发送“无设备”作为名称,并为状态 + 麦克风发送 null,“立体声耳机”/“立体声耳机”作为耳机/时的名称耳机插上。
更新:T-Mobile G1 与 1.6 的行为与 Backflip 手机相同。
Nexus 更糟糕的是,它总是为状态 + 麦克风发送 null,当耳机/耳机插入或拔出时,“耳机”作为名称。
问题:如何解释 API 在 1.5 和 2.1 版本以及不同的设备和制造商上都被破坏了这么多?
更新:
主Activity的onCreate中的代码:
// Register receiver
    this.registerReceiver(new BroadcastsHandler(), new IntentFilter(Intent.ACTION_HEADSET_PLUG));
现在广播接收器的代码:
public class BroadcastsHandler extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equalsIgnoreCase(Intent.ACTION_HEADSET_PLUG)) {
        String data = intent.getDataString();
        Bundle extraData = intent.getExtras();
        String st = intent.getStringExtra("state");
        String nm = intent.getStringExtra("name");
        String mic = intent.getStringExtra("microphone");
        String all = String.format("st=%s, nm=%s, mic=%s", st, nm, mic);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("Headset broadcast");
        builder.setMessage(all);
        builder.setPositiveButton("Okey-dokey", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
}
}