如何在 Android 设备上检查是否已插入耳机?
本示例演示如何检查是否已将耳机插入 Android 设备。
步骤 1 − 在 Android Studio 中创建新项目,转到文件 ⇒ 新项目并填写所有必需的详细信息来创建新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml 中。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Detecting headphones plug In" /> </LinearLayout>
步骤 3 − 将以下代码添加到 src/MainActivity.java 中
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
BroadcastReceiver broadcastReceiver;
boolean Microphone_Plugged_in = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
int iii;
if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
iii = intent.getIntExtra("state", -1);
if (iii == 0) {
Microphone_Plugged_in = false;
Toast.makeText(getApplicationContext(), "microphone not plugged in", Toast.LENGTH_LONG).show();
}
if (iii == 1) {
Microphone_Plugged_in = true;
Toast.makeText(getApplicationContext(), "microphone plugged in",
Toast.LENGTH_LONG).show();
}
}
}
};
IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(broadcastReceiver, receiverFilter);
}
}步骤 4 − 将以下代码添加到 androidManifest.xml 中
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
让我们尝试运行应用程序。假设您已将真实的 Android 移动设备与计算机连接。要从 Android Studio 运行应用程序,请打开一个项目活动文件并单击工具栏中的运行
图标。选择您的移动设备作为选项,然后检查您的移动设备,移动设备将显示您的默认屏幕。

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP