Android -- 检测耳机插入状态


原理                                                                                   

其实android系统在耳机插入和拔出的时候都会发送广播,所以我们要想检测耳机的状态只需要注册响应的BroadCastReceiver,对状态进行响应的判断就ok了。

这个广播的名字叫做:android.intent.action.HEADSET_PLUG

Code                                                                                   

Android -- 检测耳机插入状态
package com.yydcdut.ear;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //给广播绑定响应的过滤器  
        IntentFilter intentFilter = new IntentFilter();  
        intentFilter.addAction("android.intent.action.HEADSET_PLUG");  
        HeadsetReceiver headsetReceiver = new HeadsetReceiver();  
        registerReceiver(headsetReceiver, intentFilter);  
    }

    //自己定义的广播接收器  
    public class HeadsetReceiver extends BroadcastReceiver {  
  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            if (intent.hasExtra("state")) {  
                if (0 == intent.getIntExtra("state", 0)) {  
                    Toast.makeText(context, "耳机未插入", Toast.LENGTH_SHORT).show();  
                } else if (1 == intent.getIntExtra("state", 0)) {  
                    Toast.makeText(context, "耳机已插入", Toast.LENGTH_SHORT).show();  
                }  
            }  
        }
    }  
}
Android -- 检测耳机插入状态

我是天王盖地虎的分割线                




本文转自我爱物联网博客园博客,原文链接:http://www.cnblogs.com/yydcdut/p/3909702.html,如需转载请自行联系原作者

上一篇:Riddler助力Docker容器为runC运行环境做准备


下一篇:Docker的Save和Export的区别