zoukankan      html  css  js  c++  java
  • Android 监听耳机的插拔事件

    一般采用的是动态监听的方式来实现的:

    package com.renhui.ej;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.Toast;
    
    public class MainActivity extends AppCompatActivity {
    
        HeadsetPlugReceiver headsetPlugReceiver;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            registerHeadsetPlugReceiver();  // 注册监听
        }
    
        private void registerHeadsetPlugReceiver() {
            headsetPlugReceiver = new HeadsetPlugReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.intent.action.HEADSET_PLUG");
            registerReceiver(headsetPlugReceiver, filter);
        }
    
        @Override
        protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            unregisterReceiver(headsetPlugReceiver);  //注销监听
        }
    
    
        class HeadsetPlugReceiver extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
    
                if (intent.hasExtra("state")) {
                    if (intent.getIntExtra("state", 0) == 0) {
                        Toast.makeText(context, "headset not connected", Toast.LENGTH_LONG).show();
                    } else if (intent.getIntExtra("state", 0) == 1) {
                        Toast.makeText(context, "headset  connected", Toast.LENGTH_LONG).show();
                    }
                }
            }
    
        }
    }
  • 相关阅读:
    leetcode| Intersection of Two Arrays II
    Spring Boot起步依赖:定制starter
    SpringBoot自动配置的魔法是怎么实现的
    Dubbo中的IoC实现
    必须知道的String知识点
    Dubbo的SPI机制
    为什么要设置HTTP timeout?
    重构代码——简单工厂模式+模板方法模式
    计算机基础——位运算
    系统间HTTP调用代码封装
  • 原文地址:https://www.cnblogs.com/renhui/p/8616901.html
Copyright © 2011-2022 走看看