Android 设置中增加 OTG 开关以方便调试
在开发工作中我们经常可能需要用到USB调试,然而有些设备默认是在host模式,我们知道host之间是不能互联的,所以如果这时我们想要使用USB调试的话,需要将设备进行host与devices模式之间的切换,将模式由host切到devices,所以这时候如果我们有一个可以控制两种模式切换的 OTG 按钮开关的话,那将会对我们的调试工作十分方便,控制设备host与devices模式之间转换的具体功能代码参考如下:
package com.android.settings.accessibility;
import android.content.Context;
import android.provider.Settings;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.android.settings.Utils;
import com.android.settings.core.TogglePreferenceController;
public class UsbOrOtgPreferenceController extends TogglePreferenceController {
private final String TAG = "UsbOrOtgPreferenceController";
private String ON = "1"; // 1
private String OFF = "0"; // 0
private static final String GPIO_PATH ="devices_host_ctrl_path";
public UsbOrOtgPreferenceController(Context context, String preferenceKey) {
super(context, preferenceKey);
}
@Override
public boolean isChecked() {
return ON.equals(readFile(GPIO_PATH));
}
@Override
public boolean setChecked(boolean isChecked) {
if (isChecked) {
writeFile(ON,GPIO_PATH);
} else {
writeFile(OFF,GPIO_PATH);
}
return true;
}
@Override
public int getAvailabilityStatus() {
return AVAILABLE;
}
private void writeFile(String commod,String Path) {
BufferedWriter bufWriter;
try {
bufWriter = new BufferedWriter(new FileWriter(Path));
bufWriter.write(commod);
bufWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readFile(String Path) {
String result = "0";
BufferedReader bufReader;
try {
bufReader = new BufferedReader(new FileReader(Path));
String text = bufReader.readLine();
result = text.trim();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
重新编译验证,功能生效