我只是想檢查,如果耳機在Android設備插入插入。檢查耳機是否在Android手機
然後當我按下按鈕時,它應該檢查耳機是否插入。如果插入了耳機,那麼我會播放音頻,否則我會顯示一個吐司插入耳機,即我不會直到headhones在插入做任何事情
我只是想檢查,如果耳機在Android設備插入插入。檢查耳機是否在Android手機
然後當我按下按鈕時,它應該檢查耳機是否插入。如果插入了耳機,那麼我會播放音頻,否則我會顯示一個吐司插入耳機,即我不會直到headhones在插入做任何事情
您可以使用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;
}
}
}
}
}
我不知道如何使用這個類...我是說我怎麼能在onclick事件用這個,但我噸 –
我編輯我的答案。將'MusicIntentReceiver'放入您的活動類中,然後從'onCreate'方法創建它的實例。然後,當你短聲按鈕,您可以檢查 – Expiredmind
當我這樣做。我的應用程序崩潰了'isHeadphoneConnected'標誌是否有 –
的可能的複製。[安卓:檢查是否插入耳機(http://stackoverflow.com/questions/2764733/android - 檢查 - 如果-耳機 - 都 - 插入式) – nandsito