本文主要是通过动态注册接收系统广播。
代码如下:
代码如下:
</pre><pre name="code" class="java">public class ListenActivity extends Activity {
HeadsetReceiver myReceiver;
private TextView tvinfo;
private ImageView ig;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
tvinfo=(TextView)findViewById(R.id.info1);
ig=(ImageView)findViewById(R.id.imageView1);
myReceiver = new HeadsetReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(myReceiver, filter);
}
private class HeadsetReceiver 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:
tvinfo.setText(R.string.headset_off);
ig.setImageResource(R.drawable.off);
Log.v("ss", "Headset is unplugged");
break;
case 1:
tvinfo.setText(R.string.headset_on);
ig.setImageResource(R.drawable.on);
Log.v("ss", "Headset is plugged");
break;
default:
tvinfo.setText(R.string.headset_unknow);
Log.v("ss", "I have no idea what the headset state is");
}
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
}
}
耳机未插入。
耳机插入后