ACTION_HEADSET_PLUG不工作API棒棒糖



我使用此代码来检测耳机的插拔,在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");
}
}
}
}

解决!只是不要在android模拟器上工作,在真正的手机上工作很好,谢谢!

最新更新