【发布时间】:2019-01-24 15:25:39
【问题描述】:
我想使用 Android 上的应用检测我连接的设备。
我想检测键盘、鼠标和闪存驱动器。
我目前正在使用hwinfo 命令和定时器
//keyboard detect class.
public class detectService extends Service {
static Process hwinfo;
static String keyboard = "";
private Handler handler;
private Timer timer;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
handler = new Handler();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
String[] cmd = new String[] {"su", "-c", "hwinfo --keyboard | grep - i 'keyboard'"};
try {
hwinfo = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(hwinfo.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
line = line.trim().toLowerCase();
keyboard = line;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
if (keyboard.contains("keyboard")) {
timer.cancel();
Intent intent = new Intent(this, keyboardDialog.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
});
}
};
timer = new Timer("Service");
timer.scheduleAtFixedRate(timerTask, 0 , 4000);
}
此源代码可以很好地检测键盘。 但它每 4 秒执行一次。
我不想在连接键盘、鼠标和闪存驱动器时使用计时器。
检测连接在 android 上的设备。
事件检测或接收器。
如何不使用 Timer 来检测 android 上连接的设备?
【问题讨论】:
标签: android