检查耳机是否插入Android手机

时间:2017-03-17 10:52:31

标签: android

我只想检查耳机是否插入Android设备。

然后当我按下按钮时,应该检查耳机是否已插入。如果已插入,我会播放音频,否则我会显示一个吐司插入耳机,即我不会这样做任何东西,直到耳机插入。

1 个答案:

答案 0 :(得分:2)

您可以使用BroadcastReceiver

  public class MainActivity extends AppCompatActivity {
    private MusicIntentReceiver myReceiver;
  boolean  isHeadphoneConnected;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        MusicIntentReceiver myReceiver = new MusicIntentReceiver();
        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(myReceiver, filter);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            if(isHeadphoneConnected)
                Toast.makeText(MainActivity.this,"Headset is plug in",Toast.LENGTH_LONG).show();
                else
                Toast.makeText(MainActivity.this,"Headset is not plug in",Toast.LENGTH_LONG).show();
            }
        });
    }
    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:
                        isHeadphoneConnected = false;

                    break;
                    case 1:
                        isHeadphoneConnected = true;
                        break;
                }
            }
        }
    }
}