ACTION_HEADSET_PLUG无法正常使用API​​棒棒糖

时间:2018-11-29 21:18:23

标签: android-intent broadcastreceiver headset

我正在使用此代码来检测耳机的插入/拔出,在API> = 24中工作正常,但是在API 21、22、23中尝试崩溃时却什么也没检测到。您可以帮助我

public class MainActivity extends Activity  {
private static final String TAG = "MainActivity";
private MusicIntentReceiver myReceiver;

@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myReceiver = new MusicIntentReceiver();
}

@Override public void onResume() {
    IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    registerReceiver(myReceiver, filter);
    super.onResume();
}

private 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(TAG, "Headset is unplugged");
                break;
            case 1:
                Log.d(TAG, "Headset is plugged");
                break;
            default:
                Log.d(TAG, "I have no idea what the headset state is");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

下定决心!只是不能在android模拟器上使用,在真实手机上可以正常工作,谢谢!